// app/api/internal/foreign-student/delete-appointment/[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 DELETE(
  req: NextRequest,
  { params }: PageProps
) {
  const connection = await pool.getConnection();
  
  try {

    const {id} = await params;

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

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

    // Check if user is authorized (foreign student)
    if (decoded.role !== 'foreign-student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    const foreignStudentId = decoded.id;

    // Start transaction
    await connection.beginTransaction();

    // 1. Check if appointment exists, belongs to this foreign student, and is not completed
    const [appointment] = await connection.query<RowDataPacket[]>(
      `SELECT fsbs.id, s.first_name as student_name, fsbs.status
       FROM foreign_student_booked_sessions fsbs
       INNER JOIN users s ON fsbs.student_id = s.id
       WHERE fsbs.id = ? AND fsbs.foreign_student_id = ?`,
      [appointmentId, foreignStudentId]
    );

    if (appointment.length === 0) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Appointment not found or access denied' },
        { status: 404 }
      );
    }

    // 2. Check if appointment is completed (cannot delete completed appointments)
    if (appointment[0].status === 'completed') {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Cannot delete completed appointments' },
        { status: 400 }
      );
    }

    // 3. Check if appointment is in the past (only past appointments can be deleted)
    const [appointmentDetails] = await connection.query<RowDataPacket[]>(
      `SELECT session_date, start_time 
       FROM foreign_student_booked_sessions 
       WHERE id = ?`,
      [appointmentId]
    );

    const appointmentDate = new Date(appointmentDetails[0].session_date);
    const appointmentTime = appointmentDetails[0].start_time;
    const currentTime = new Date();
    
    // Combine date and time for comparison
    const [hours, minutes] = appointmentTime.split(':');
    appointmentDate.setHours(parseInt(hours), parseInt(minutes), 0, 0);
    
    // Only allow deletion of past appointments
    if (appointmentDate > currentTime) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Can only delete past appointments' },
        { status: 400 }
      );
    }

    // 4. Delete the appointment
    await connection.query(
      'DELETE FROM foreign_student_booked_sessions WHERE id = ? AND foreign_student_id = ?',
      [appointmentId, foreignStudentId]
    );

    // Commit transaction
    await connection.commit();
    connection.release();

    return NextResponse.json({
      success: true,
      message: 'Appointment deleted successfully'
    }, { status: 200 });

  } catch (err: any) {
    // Rollback on any error
    if (connection) {
      await connection.rollback();
      connection.release();
    }
    
    console.error('Delete appointment error:', err);
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to delete appointment' 
      },
      { status: 500 }
    );
  }
}