// app/api/appapis/foreign-student-appointments/route.js
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';

// CORS headers
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key',
  'Access-Control-Allow-Credentials': 'true',
};

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // Get token from Authorization header for mobile app
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'No valid authorization header found' },
        { status: 401, headers: corsHeaders }
      );
    }

    const token = authHeader.substring(7);
    
    // Verify token
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      connection.release();
      return authResult;
    }
    
    const decoded = authResult as { id: number; role: string };
    
    if (!decoded || !decoded.id) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid token - no user ID found' },
        { status: 401, headers: corsHeaders }
      );
    }

    if (decoded.role !== 'foreign-student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied. Foreign student access only.' },
        { status: 403, headers: corsHeaders }
      );
    }

    const foreignStudentId = decoded.id;

    // Check if foreign student exists
    const [studentExists] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM foreign_students WHERE id = ? AND is_active = 1',
      [foreignStudentId]
    );

    if (studentExists.length === 0) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Foreign student not found or inactive' },
        { status: 404, headers: corsHeaders }
      );
    }

    // Fetch foreign student appointments with student details
    const [appointments] = await connection.query<RowDataPacket[]>(
      `SELECT 
        fsbs.id,
        fsbs.session_date,
        fsbs.start_time,
        fsbs.end_time,
        fsbs.amount,
        fsbs.status,
        fsbs.meeting_link,
        fsbs.notes,
        fsbs.created_at,
        fsbs.updated_at,
        s.id as student_id,
        s.first_name as student_first_name,
        s.last_name as student_last_name,
        s.email as student_email,
        s.image as student_profile_picture
      FROM foreign_student_booked_sessions fsbs
      INNER JOIN users s ON fsbs.student_id = s.id
      WHERE fsbs.foreign_student_id = ?
      ORDER BY 
        CASE 
          WHEN fsbs.session_date >= CURDATE() THEN 0
          ELSE 1
        END,
        fsbs.session_date DESC,
        fsbs.start_time ASC`,
      [foreignStudentId]
    );

    connection.release();

    // Format appointments for mobile app
    const formattedAppointments = appointments.map(app => ({
      id: app.id,
      session_date: app.session_date instanceof Date 
        ? app.session_date.toISOString().split('T')[0] 
        : app.session_date,
      start_time: app.start_time ? app.start_time.substring(0, 5) : '00:00',
      end_time: app.end_time ? app.end_time.substring(0, 5) : '00:00',
      amount: parseFloat(app.amount) || 0,
      status: app.status,
      meeting_link: app.meeting_link || null,
      notes: app.notes || null,
      created_at: app.created_at,
      updated_at: app.updated_at,
      student_id: app.student_id,
      student_name: `${app.student_first_name || ''} ${app.student_last_name || ''}`.trim(),
      student_email: app.student_email,
      student_profile_picture: app.student_profile_picture || null
    }));

    return NextResponse.json({
      success: true,
      message: 'Appointments fetched successfully',
      appointments: formattedAppointments,
      counts: {
        total: formattedAppointments.length,
        pending: formattedAppointments.filter(a => a.status === 'pending').length,
        confirmed: formattedAppointments.filter(a => a.status === 'confirmed').length,
        completed: formattedAppointments.filter(a => a.status === 'completed').length,
        cancelled: formattedAppointments.filter(a => a.status === 'cancelled').length,
        upcoming: formattedAppointments.filter(a => new Date(a.session_date) >= new Date()).length
      }
    }, { status: 200, headers: corsHeaders });

  } catch (err: any) {
    if (connection) connection.release();
    console.error('Get foreign student appointments error:', err);
    return NextResponse.json(
      { 
        success: false, 
        message: err.message || 'Failed to fetch appointments' 
      },
      { status: 500, headers: corsHeaders }
    );
  }
}