// app/api/internal/student/foreign-student-availability/[id]/route.js
import pool from '../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';

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

export async function GET(
  req: NextRequest,
  { params }: PageProps
) {
  const connection = await pool.getConnection();
  
  try {
    const {id} = await params;
    
    if (!id) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid foreign student ID' },
        { status: 400 }
      );
    }

    const foreignStudentId = id;
    
    if (!foreignStudentId) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid foreign student ID' },
        { status: 400 }
      );
    }

    // Get month parameter from query
    const { searchParams } = new URL(req.url);
    const monthParam = searchParams.get('month');
    
    let startDate = new Date();
    let endDate = new Date();
    
    if (monthParam) {
      // Parse the month parameter
      startDate = new Date(monthParam);
      startDate.setDate(1); // First day of the month
      endDate = new Date(startDate);
      endDate.setMonth(endDate.getMonth() + 1);
      endDate.setDate(0); // Last day of the month
    } else {
      // Default: next 60 days
      endDate.setDate(endDate.getDate() + 60);
    }

    const startDateStr = startDate.toISOString().split('T')[0];
    const endDateStr = endDate.toISOString().split('T')[0];

    // Token verification (optional)
    const token = req.cookies.get('university-token')?.value;
    if (token) {
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
        // You can use decoded info if needed
      } catch (err) {
        // Token verification is optional for this endpoint
      }
    }

    // Fetch weekly schedule
    const [weeklyScheduleRows] = await connection.query<RowDataPacket[]>(
      `SELECT 
        id,
        day_of_week, 
        is_available
       FROM foreign_student_weekly_schedule
       WHERE foreign_student_id = ?
       ORDER BY day_of_week`,
      [foreignStudentId]
    );

    // Fetch time slots for each schedule
    const processedSchedule = await Promise.all(
      weeklyScheduleRows.map(async (day) => {
        const [timeSlots] = await connection.query<RowDataPacket[]>(
          `SELECT start_time, end_time 
           FROM foreign_student_time_slots 
           WHERE weekly_schedule_id = ?
           ORDER BY start_time`,
          [day.id]
        );

        return {
          day_of_week: day.day_of_week,
          is_available: day.is_available,
          time_slots: timeSlots.map(slot => ({
            start: slot.start_time.substring(0, 5),
            end: slot.end_time.substring(0, 5)
          }))
        };
      })
    );

    // Fetch special dates for the date range
    const [specialDatesRows] = await connection.query<RowDataPacket[]>(
      `SELECT 
        id,
        date,
        type,
        reason
       FROM foreign_student_special_dates
       WHERE foreign_student_id = ?
       AND date >= ?
       AND date <= ?
       ORDER BY date ASC`,
      [foreignStudentId, startDateStr, endDateStr]
    );

    // Fetch time slots for each special date
    const processedSpecialDates = await Promise.all(
      specialDatesRows.map(async (date) => {
        const [timeSlots] = await connection.query<RowDataPacket[]>(
          `SELECT start_time, end_time 
           FROM foreign_student_special_date_slots 
           WHERE special_date_id = ?
           ORDER BY start_time`,
          [date.id]
        );

        return {
          id: date.id,
          date: date.date,
          type: date.type,
          reason: date.reason,
          time_slots: timeSlots.map(slot => ({
            start: slot.start_time.substring(0, 5),
            end: slot.end_time.substring(0, 5)
          }))
        };
      })
    );

    // Fetch already booked sessions for the date range
    // IMPORTANT: Fix the date format to match YYYY-MM-DD
    const [bookedSessions] = await connection.query<RowDataPacket[]>(
      `SELECT 
        id,
        DATE(session_date) as session_date,  -- Use DATE() to get just the date part
        start_time, 
        end_time,
        status,
        student_id
       FROM foreign_student_booked_sessions
       WHERE foreign_student_id = ?
       AND session_date >= ?
       AND session_date <= ?
       AND status IN ('pending', 'confirmed', 'scheduled')
       ORDER BY session_date, start_time`,
      [foreignStudentId, startDateStr, endDateStr]
    );

    connection.release();

    return NextResponse.json({
      success: true,
      message: 'Availability fetched successfully',
      schedule: processedSchedule,
      specialDates: processedSpecialDates,
      bookedSessions: bookedSessions.map(session => ({
        id: session.id,
        date: session.session_date,  // This will now be in YYYY-MM-DD format
        start: session.start_time.substring(0, 5),
        end: session.end_time.substring(0, 5),
        status: session.status,
        student_id: session.student_id
      })),
      dateRange: {
        start: startDateStr,
        end: endDateStr
      }
    }, { status: 200 });

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