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

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

export async function POST(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 studentId = body.id;
    
    if (!studentId) {
      return NextResponse.json({
        success: false,
        message: "Student ID is required"
      }, { status: 400 });
    }
    
    // Get database connection
    connection = await pool.getConnection();
    
    // Get consultant ID from consultants table using user_id
    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;
    
    // Fetch student details
    const [rows] = 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,
        intial_documents_assessment,
        course_finalaztion,
        application_submitted,
        got_admission,
        visa_applied,
        case_closed,
        created_at,
        updated_at
      FROM cstudents 
      WHERE id = ? AND consultant_id = ?`,
      [studentId, consultantId]
    ) as RowDataPacket[];
    
    if (rows.length === 0) {
      return NextResponse.json({
        success: false,
        message: "Student not found or access denied"
      }, { status: 404 });
    }
    
    const student = rows[0];
    
    // Calculate stage-based status
    const stages = [
      student.intial_documents_assessment === 'on',
      student.course_finalaztion === 'on',
      student.application_submitted === 'on',
      student.got_admission === 'on',
      student.visa_applied === 'on',
      student.case_closed === 'on',
    ];
    
    const anyStageStarted = stages.some(stage => stage === true);
    const stageStatus = anyStageStarted ? 'started' : 'pending';
    
    // Find current stage (last completed stage)
    const stageNames = [
      'Initial Assessment',
      'Course Finalized', 
      'Application Submitted',
      'Got Admission',
      'Visa Applied',
      'Case Closed'
    ];
    
    let currentStage = 'Initial Assessment';
    for (let i = stages.length - 1; i >= 0; i--) {
      if (stages[i]) {
        currentStage = stageNames[i];
        break;
      }
    }
    
    // Format response data
    const studentData = {
      id: student.id,
      name: student.name,
      email: student.email || '',
      phone: student.phone || '',
      passport_number: student.passport_number,
      date_of_birth: student.date_of_birth || '',
      nationality: student.nationality || '',
      university: student.university || '',
      course_doc: student.course_doc,
      intrested_country_doc: student.intrested_country_doc,
      passport_doc: student.passport_doc || '',
      photo_doc: student.photo_doc || '',
      educational_degree_doc: student.educational_degree_doc || '',
      educational_certificate_doc: student.educational_certificate_doc || '',
      recomendation_letter_doc: student.recomendation_letter_doc || '',
      study_plan: student.study_plan || '',
      ielts_english_proficiency_letter: student.ielts_english_proficiency_letter || '',
      status: student.status || 'pending',
      stage_status: stageStatus,
      current_stage: currentStage,
      created_at: student.created_at,
      updated_at: student.updated_at,
      application_stages: {
        intial_documents_assessment: student.intial_documents_assessment === 'on',
        course_finalaztion: student.course_finalaztion === 'on',
        application_submitted: student.application_submitted === 'on',
        got_admission: student.got_admission === 'on',
        visa_applied: student.visa_applied === 'on',
        case_closed: student.case_closed === 'on',
      }
    };
    
    return NextResponse.json({
      success: true,
      message: "Student details retrieved successfully",
      data: studentData
    }, { status: 200 });
    
  } catch (error) {
    console.error('Error fetching student details:', 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();
    }
  }
}