// app/api/appapis/consultant_student_list/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 });
    }
    
    // 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;
    
    // Fetch all students for this consultant - FIXED: removed generic type parameter
    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, created_at, updated_at,
        intial_documents_assessment, course_finalaztion, 
        application_submitted, got_admission, visa_applied, case_closed
      FROM cstudents 
      WHERE consultant_id = ? 
      ORDER BY created_at DESC`,
      [consultantId]
    ) as RowDataPacket[];
    
    // Add stage-based status to each student
    const transformedData = rows.map(row => {
      const stages = [
        row.intial_documents_assessment === 'on',
        row.course_finalaztion === 'on',
        row.application_submitted === 'on',
        row.got_admission === 'on',
        row.visa_applied === 'on',
        row.case_closed === 'on',
      ];
      const anyStageStarted = stages.some(stage => stage === true);
      const stageStatus = anyStageStarted ? 'started' : 'pending';
      
      // Find current 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;
        }
      }
      
      return {
        id: row.id,
        name: row.name,
        email: row.email || '',
        phone: row.phone || '',
        passport_number: row.passport_number,
        date_of_birth: row.date_of_birth || '',
        nationality: row.nationality || '',
        university: row.university || '',
        course_doc: row.course_doc,
        intrested_country_doc: row.intrested_country_doc,
        passport_doc: row.passport_doc || '',
        photo_doc: row.photo_doc || '',
        educational_degree_doc: row.educational_degree_doc || '',
        educational_certificate_doc: row.educational_certificate_doc || '',
        recomendation_letter_doc: row.recomendation_letter_doc || '',
        study_plan: row.study_plan || '',
        ielts_english_proficiency_letter: row.ielts_english_proficiency_letter || '',
        status: row.status || 'pending',
        stage_status: stageStatus,
        current_stage: currentStage,
        created_at: row.created_at,
        updated_at: row.updated_at
      };
    });
    
    return NextResponse.json({
      success: true,
      message: "Students retrieved successfully",
      data: transformedData,
      total: transformedData.length
    }, { status: 200 });
    
  } catch (error) {
    console.error('Error fetching students:', 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();
    }
  }
}