// app/api/frontend/foreign-student/change-password/route.js
import pool from '../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import { z } from 'zod';

// Password validation schema
const passwordSchema = z.string()
  .min(8, 'Password must be at least 8 characters')
  .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
  .regex(/[a-z]/, 'Password must contain at least one lowercase letter')
  .regex(/[0-9]/, 'Password must contain at least one number')
  .regex(/[^A-Za-z0-9]/, 'Password must contain at least one special character');

// Change password validation schema
const changePasswordSchema = z.object({
  current_password: z.string().min(1, 'Current password is required'),
  new_password: passwordSchema,
  confirm_password: z.string().min(1, 'Please confirm your new password'),
}).refine((data) => data.new_password === data.confirm_password, {
  message: "Passwords don't match",
  path: ["confirm_password"],
}).refine((data) => data.current_password !== data.new_password, {
  message: "New password must be different from current password",
  path: ["new_password"],
});

export async function POST(req: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // Get token from cookie
    const token = req.cookies.get('university-token')?.value;
    
    if (!token) {
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Authentication required' 
        },
        { status: 401 }
      );
    }

    // Verify token
    let decoded;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (err) {
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Invalid or expired token' 
        },
        { status: 401 }
      );
    }

    // Check if user is a foreign student
    if (decoded.role !== 'foreign-student') {
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Access denied' 
        },
        { status: 403 }
      );
    }

    const body = await req.json();
    
    // Validate input
    const validatedData = changePasswordSchema.parse(body);

    // Get current user data with password hash
    const [userData] = await connection.query<RowDataPacket[]>(
      `SELECT id, email, password_hash 
       FROM foreign_students 
       WHERE id = ? AND is_active = 1 
       LIMIT 1`,
      [decoded.id]
    );

    if (userData.length === 0) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'User not found or account inactive' 
        },
        { status: 404 }
      );
    }

    const user = userData[0];

    // Verify current password
    const isCurrentPasswordValid = await bcrypt.compare(
      validatedData.current_password, 
      user.password_hash
    );

    if (!isCurrentPasswordValid) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Current password is incorrect' 
        },
        { status: 401 }
      );
    }

    // Hash the new password
    const salt = await bcrypt.genSalt(10);
    const newPasswordHash = await bcrypt.hash(validatedData.new_password, salt);

    // Update password in database
    await connection.query(
      `UPDATE foreign_students 
       SET password_hash = ?, updated_at = NOW() 
       WHERE id = ?`,
      [newPasswordHash, decoded.id]
    );
    
    // Clear the current token cookie
    const response = NextResponse.json({
      success: true,
      message: 'Password updated successfully. Please login again.'
    }, { status: 200 });

    // Clear the authentication cookie
    response.cookies.set('university-token', '', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/',
      expires: new Date(0)
    });
    connection.release();

    return response;

  } catch (err: any) {
    
    console.error('Password change error:', err);
    
    // Zod validation errors
    if (err instanceof z.ZodError) {
      const errors = {};
      err.errors.forEach(error => {
        const path = error.path.join('.');
        errors[path] = error.message;
      });
      
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Validation failed', 
          errors 
        },
        { status: 400 }
      );
    }
    
    // Database or other errors
    connection.release();
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to change password' 
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}