// app/api/frontend/userdashboard/student-appointments/route.js
import pool from '../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';

export async function GET(req: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // Get token from cookie
    const token = req.cookies.get('university-token')?.value;
    
    if (!token) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Authentication required' },
        { status: 401 }
      );
    }

    // Verify token
    let decoded;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (err) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid or expired token' },
        { status: 401 }
      );
    }

    if (decoded.role !== 'student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    const studentId = decoded.id;

    // 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
       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();

    return NextResponse.json({
      success: true,
      message: 'Appointments fetched successfully',
      appointments: appointments.map(app => ({
        id: app.id,
        session_date: app.session_date,
        start_time: app.start_time.substring(0, 5),
        end_time: app.end_time.substring(0, 5),
        amount: app.amount,
        status: app.status,
        notes: app.notes,
        student_feedback: app.student_feedback,
        meeting_link: app.meeting_link,
        created_at: app.created_at,
        updated_at: app.updated_at,
        tutor_name: app.tutor_name,
        tutor_profile_picture: app.tutor_profile_picture,
        rate: app.tutor_hour_rate
      }))
    }, { status: 200 });

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