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

type PageProps = {
  params: Promise<{
    id: string;
  }>;
};

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

export async function POST(request: NextRequest, { params }: PageProps) {
  let connection;
  
  try {
    const { id } = await params;
    
    // Get token from multiple sources
    let token = null;
    
    const authHeader = request.headers.get('authorization');
    if (authHeader && authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    }
    
    if (!token) {
      token = request.cookies.get("university-token")?.value || null;
    }
    
    if (!token) {
      const url = new URL(request.url);
      token = url.searchParams.get('token');
    }
    
    if (!token) {
      return NextResponse.json(
        {
          success: false,
          message: "No authentication token found"
        },
        { status: 401 }
      );
    }
    
    const decoded = await verifyAuthentication(token);
    
    if (decoded instanceof NextResponse) {
      return decoded;
    }
    
    if (!decoded || decoded.role !== "consultant") {
      return NextResponse.json(
        {
          success: false,
          message: "Unauthorized access. Consultant role required."
        },
        { status: 403 }
      );
    }
    
    connection = await pool.getConnection();
    
    // Get consultant ID from consultants table - 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 student with consultant verification - FIXED: removed generic type parameter
    const [rows] = await connection.query(
      `SELECT 
        id, 
        name, 
        passport_number, 
        course_doc, 
        intrested_country_doc,
        status,
        created_at, 
        updated_at,
        intial_documents_assessment, 
        course_finalaztion, 
        application_submitted, 
        got_admission, 
        visa_applied, 
        case_closed
      FROM cstudents 
      WHERE id = ? AND consultant_id = ?`,
      [id, 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];
    
    // Define stages in order
    const stageKeys = [
      'intial_documents_assessment',
      'course_finalaztion',
      'application_submitted',
      'got_admission',
      'visa_applied',
      'case_closed'
    ];
    
    const stageNames = [
      'Initial Assessment',
      'Course Finalized',
      'Application Submitted',
      'Got Admission',
      'Visa Applied',
      'Case Closed'
    ];
    
    // Check which stages are completed
    const stagesCompleted = stageKeys.map(key => {
      const value = student[key];
      return value === 'on' || value === 1 || value === true;
    });
    
    // Calculate stage-based status
    const anyStageStarted = stagesCompleted.some(completed => completed === true);
    const stageStatus = anyStageStarted ? 'started' : 'pending';
    
    // Find current stage
    let currentStage = 'Initial Assessment';
    let currentStageIndex = -1;
    
    for (let i = stagesCompleted.length - 1; i >= 0; i--) {
      if (stagesCompleted[i]) {
        currentStage = stageNames[i];
        currentStageIndex = i;
        break;
      }
    }
    
    // Build application stages object
    const applicationStages: Record<string, boolean> = {};
    stageKeys.forEach((key, index) => {
      applicationStages[key] = stagesCompleted[index];
    });
    
    const reportData = {
      id: student.id,
      name: student.name,
      passport_number: student.passport_number,
      course_doc: student.course_doc,
      intrested_country_doc: student.intrested_country_doc,
      stage_status: stageStatus,
      current_stage: currentStage,
      current_stage_index: currentStageIndex,
      created_at: student.created_at,
      updated_at: student.updated_at,
      application_stages: applicationStages,
      intial_documents_assessment: stagesCompleted[0],
      course_finalaztion: stagesCompleted[1],
      application_submitted: stagesCompleted[2],
      got_admission: stagesCompleted[3],
      visa_applied: stagesCompleted[4],
      case_closed: stagesCompleted[5]
    };
    
    return NextResponse.json(
      {
        success: true,
        message: "Student report retrieved successfully",
        data: reportData
      },
      { status: 200 }
    );
    
  } catch (error) {
    console.error('Error fetching student report:', 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();
  }
}