// app/api/appapis/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 }
      );
    }

    // Check if user is a student
    if (decoded.role !== 'student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied. Student access only.' },
        { status: 403, headers: corsHeaders }
      );
    }

    const studentId = decoded.id;

    // Check if student exists and is active
    const [studentExists] = await connection.query<RowDataPacket[]>(
      'SELECT id, first_name, last_name, email FROM users WHERE id = ? AND is_active = 1 AND user_type = "student"',
      [studentId]
    );

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

    // Fetch student appointments with tutor 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.student_feedback,
        fsbs.notes,
        fsbs.created_at,
        fsbs.updated_at,
        fs.id as tutor_id,
        fs.name as tutor_name,
        fs.profile_picture as tutor_profile_picture,
        fs.hour_rate as tutor_hour_rate,
        fs.country_id,
        fs.experience,
        fs.last_education
      FROM foreign_student_booked_sessions fsbs
      INNER JOIN foreign_students fs ON fsbs.foreign_student_id = fs.id
      WHERE fsbs.student_id = ?
      ORDER BY 
        CASE 
          WHEN fsbs.session_date >= CURDATE() THEN 0
          ELSE 1
        END,
        fsbs.session_date DESC,
        fsbs.start_time ASC`,
      [studentId]
    );

    connection.release();

    // Helper function to format time
    const formatTime = (timeString: string | null) => {
      if (!timeString) return '00:00';
      return timeString.substring(0, 5);
    };

    // Helper function to format date
    const formatDateForResponse = (date: any) => {
      if (date instanceof Date) {
        return date.toISOString().split('T')[0];
      }
      return date;
    };

    // Get current date for upcoming/past calculations
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // Format appointments and add computed fields
    const formattedAppointments = appointments.map(app => {
      const appointmentDate = new Date(app.session_date);
      const isPast = appointmentDate < today;
      const canCancel = ['pending', 'confirmed', 'scheduled'].includes(app.status) && !isPast;
      const canJoin = app.meeting_link && ['confirmed', 'scheduled'].includes(app.status) && !isPast;
      
      return {
        id: app.id,
        session_date: formatDateForResponse(app.session_date),
        start_time: formatTime(app.start_time),
        end_time: formatTime(app.end_time),
        amount: parseFloat(app.amount) || 0,
        status: app.status,
        meeting_link: app.meeting_link || null,
        student_feedback: app.student_feedback || null,
        notes: app.notes || null,
        created_at: app.created_at,
        updated_at: app.updated_at,
        tutor_id: app.tutor_id,
        tutor_name: app.tutor_name,
        tutor_profile_picture: app.tutor_profile_picture || null,
        rate: parseFloat(app.tutor_hour_rate) || 0,
        tutor_experience: app.experience || null,
        tutor_education: app.last_education || null,
        is_past: isPast,
        can_cancel: canCancel,
        can_join: canJoin
      };
    });

    // Calculate statistics
    const totalAppointments = formattedAppointments.length;
    const upcomingCount = formattedAppointments.filter(app => !app.is_past && app.status !== 'cancelled' && app.status !== 'completed').length;
    const completedCount = formattedAppointments.filter(app => app.status === 'completed').length;
    const cancelledCount = formattedAppointments.filter(app => app.status === 'cancelled').length;
    const pendingCount = formattedAppointments.filter(app => app.status === 'pending').length;
    const confirmedCount = formattedAppointments.filter(app => app.status === 'confirmed' || app.status === 'scheduled').length;
    
    const totalSpent = formattedAppointments
      .filter(app => app.status === 'completed')
      .reduce((sum, app) => sum + (app.amount || 0), 0);
    
    const upcomingTotalAmount = formattedAppointments
      .filter(app => !app.is_past && app.status !== 'cancelled')
      .reduce((sum, app) => sum + (app.amount || 0), 0);

    // Group appointments by month for calendar view
    const appointmentsByMonth: Record<string, any[]> = {};
    formattedAppointments.forEach(app => {
      const monthKey = app.session_date.substring(0, 7); // YYYY-MM
      if (!appointmentsByMonth[monthKey]) {
        appointmentsByMonth[monthKey] = [];
      }
      appointmentsByMonth[monthKey].push(app);
    });

    return NextResponse.json({
      success: true,
      message: 'Appointments fetched successfully',
      appointments: formattedAppointments,
      appointments_by_month: appointmentsByMonth,
      stats: {
        total: totalAppointments,
        upcoming: upcomingCount,
        completed: completedCount,
        cancelled: cancelledCount,
        pending: pendingCount,
        confirmed: confirmedCount,
        total_spent: totalSpent,
        upcoming_total_amount: upcomingTotalAmount
      },
      student_info: {
        id: studentExists[0].id,
        name: `${studentExists[0].first_name} ${studentExists[0].last_name}`,
        email: studentExists[0].email
      }
    }, { status: 200, headers: corsHeaders });

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