// app/api/appapis/consultant_student_edit/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 });
}

export async function PUT(request: NextRequest) {
  let connection;
  
  try {
    // Get token from Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { status: 401 });
    }

    const token = authHeader.substring(7);
    
    // Verify authentication
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as { id: number; role: string };
    
    if (!decoded || decoded.role !== "consultant") {
      return NextResponse.json({
        success: false,
        message: "Unauthorized access. Consultant role required."
      }, { status: 403 });
    }
    
    // Parse request body
    const body = await request.json();
    const { 
      id, 
      name, 
      email, 
      phone, 
      passportNumber, 
      dateOfBirth, 
      nationality, 
      university, 
      course, 
      country, 
      files 
    } = body;
    
    if (!id) {
      return NextResponse.json({
        success: false,
        message: "Student ID is required"
      }, { status: 400 });
    }
    
    // Validate required fields
    if (!name || !passportNumber || !course || !country) {
      return NextResponse.json({
        success: false,
        message: "Missing required fields: name, passportNumber, course, country"
      }, { status: 400 });
    }
    
    // Get database connection
    connection = await pool.getConnection();
    
    // Get consultant ID - FIXED: removed generic type parameter
    const [consultantRows] = await connection.query(
      "SELECT id FROM consultants WHERE user_id = ?",
      [decoded.id]
    ) as RowDataPacket[];
    
    if (consultantRows.length === 0) {
      return NextResponse.json({
        success: false,
        message: "Consultant profile not found"
      }, { status: 404 });
    }
    
    const consultantId = decoded.id;
    
    // Check if student exists and belongs to this consultant - FIXED: removed generic type parameter
    const [checkRows] = await connection.query(
      "SELECT id FROM cstudents WHERE id = ? AND consultant_id = ?",
      [id, consultantId]
    ) as RowDataPacket[];
    
    if (checkRows.length === 0) {
      return NextResponse.json({
        success: false,
        message: "Student not found or access denied"
      }, { status: 404 });
    }
    
    // Start transaction
    await connection.beginTransaction();
    
    // Build update query
    const updateFields: string[] = [];
    const updateValues: any[] = [];
    
    // Basic Information
    if (name) {
      updateFields.push("name = ?");
      updateValues.push(name);
    }
    
    if (email !== undefined) {
      updateFields.push("email = ?");
      updateValues.push(email || null);
    }
    
    if (phone !== undefined) {
      updateFields.push("phone = ?");
      updateValues.push(phone || null);
    }
    
    if (passportNumber) {
      updateFields.push("passport_number = ?");
      updateValues.push(passportNumber);
    }
    
    if (dateOfBirth !== undefined) {
      updateFields.push("date_of_birth = ?");
      updateValues.push(dateOfBirth || null);
    }
    
    if (nationality !== undefined) {
      updateFields.push("nationality = ?");
      updateValues.push(nationality || null);
    }
    
    if (university !== undefined) {
      updateFields.push("university = ?");
      updateValues.push(university || null);
    }
    
    if (course) {
      updateFields.push("course_doc = ?");
      updateValues.push(course);
    }
    
    if (country) {
      updateFields.push("intrested_country_doc = ?");
      updateValues.push(country);
    }
    
    // Document files
    if (files) {
      if (files.passport !== undefined) {
        updateFields.push("passport_doc = ?");
        updateValues.push(files.passport || null);
      }
      if (files.photo !== undefined) {
        updateFields.push("photo_doc = ?");
        updateValues.push(files.photo || null);
      }
      if (files.degree !== undefined) {
        updateFields.push("educational_degree_doc = ?");
        updateValues.push(files.degree || null);
      }
      if (files.certificate !== undefined) {
        updateFields.push("educational_certificate_doc = ?");
        updateValues.push(files.certificate || null);
      }
      if (files.recommendation !== undefined) {
        updateFields.push("recomendation_letter_doc = ?");
        updateValues.push(files.recommendation || null);
      }
      if (files.studyPlan !== undefined) {
        updateFields.push("study_plan = ?");
        updateValues.push(files.studyPlan || null);
      }
      if (files.ielts !== undefined) {
        updateFields.push("ielts_english_proficiency_letter = ?");
        updateValues.push(files.ielts || null);
      }
    }
    
    updateFields.push("updated_at = NOW()");
    
    if (updateFields.length === 0) {
      await connection.rollback();
      return NextResponse.json({
        success: false,
        message: "No fields to update"
      }, { status: 400 });
    }
    
    const query = `UPDATE cstudents SET ${updateFields.join(", ")} WHERE id = ? AND consultant_id = ?`;
    updateValues.push(id, consultantId);
    
    // FIXED: removed generic type parameter
    const [result] = await connection.query(query, updateValues) as ResultSetHeader[];
    
    if (result.affectedRows === 0) {
      await connection.rollback();
      return NextResponse.json({
        success: false,
        message: "Failed to update student"
      }, { status: 500 });
    }
    
    // Commit transaction
    await connection.commit();
    
    // Fetch updated student data - FIXED: removed generic type parameter
    const [updatedRows] = await connection.query(
      `SELECT 
        id, name, email, phone, passport_number, date_of_birth,
        nationality, university, course_doc, intrested_country_doc,
        passport_doc, photo_doc, educational_degree_doc, educational_certificate_doc,
        recomendation_letter_doc, study_plan, ielts_english_proficiency_letter,
        status, created_at, updated_at
      FROM cstudents 
      WHERE id = ? AND consultant_id = ?`,
      [id, consultantId]
    ) as RowDataPacket[];
    
    return NextResponse.json({
      success: true,
      message: "Student updated successfully",
      data: updatedRows[0]
    }, { status: 200 });
    
  } catch (error) {
    if (connection) {
      await connection.rollback();
    }
    console.error('Error updating student:', error);
    return NextResponse.json({
      success: false,
      message: "Internal server error",
      error: process.env.NODE_ENV === 'development' ? (error as Error).message : undefined
    }, { status: 500 });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}