// app/api/frontend/userdashboard/cancel-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 POST(
  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 (student)
    if (decoded.role !== 'student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    const studentId = decoded.id;

    // Start transaction
    await connection.beginTransaction();

    // 1. Check if appointment exists and belongs to this student
    const [appointment] = await connection.query<RowDataPacket[]>(
      `SELECT fsbs.id, fs.name as tutor_name, fs.email as tutor_email
       FROM foreign_student_booked_sessions fsbs
       INNER JOIN foreign_students fs ON fsbs.foreign_student_id = fs.id
       WHERE fsbs.id = ? AND fsbs.student_id = ?`,
      [appointmentId, studentId]
    );

    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 can be cancelled (not in past and not already cancelled/completed)
    const [appointmentDetails] = await connection.query<RowDataPacket[]>(
      `SELECT session_date, start_time, status 
       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);
    
    // Check if appointment is in the past
    if (appointmentDate < currentTime) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Cannot cancel past appointments' },
        { status: 400 }
      );
    }

    // Check if appointment is already cancelled or completed
    if (['cancelled', 'completed'].includes(appointmentDetails[0].status)) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: `Appointment is already ${appointmentDetails[0].status}` },
        { status: 400 }
      );
    }

    // 3. Update appointment status to cancelled
    await connection.query(
      `UPDATE foreign_student_booked_sessions 
       SET status = 'cancelled', updated_at = NOW()
       WHERE id = ? AND student_id = ?`,
      [appointmentId, studentId]
    );

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

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

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