// app/api/appapis/update-meeting-link/[id]/route.js
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../../lib/db/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { verifyAuthentication } from '../../../../utils/verifyAuthentication';
import { z } from 'zod';

// Validation schema for meeting link
const meetingLinkSchema = z.object({
  meeting_link: z.string()
    .url('Please enter a valid URL')
    .min(5, 'Meeting link is required')
    .max(500, 'Meeting link is too long')
});

// 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 POST(
  request: NextRequest,
  { params }
) {
  const connection = await pool.getConnection();
  
  try {
    const appointmentId = params.id;
    
    if (!appointmentId) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid appointment ID' },
        { status: 400, headers: corsHeaders }
      );
    }

    // 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 authorized (foreign student)
    if (decoded.role !== 'foreign-student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied. Foreign student access only.' },
        { status: 403, headers: corsHeaders }
      );
    }

    const foreignStudentId = decoded.id;
    
    // Check if foreign student exists and is active
    const [studentExists] = await connection.query<RowDataPacket[]>(
      'SELECT id, name, email FROM foreign_students WHERE id = ? AND is_active = 1',
      [foreignStudentId]
    );

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

    const body = await request.json();
    
    // Validate input
    const validatedData = meetingLinkSchema.parse(body);

    // Start transaction
    await connection.beginTransaction();

    // 1. Check if appointment exists and belongs to this foreign student
    const [appointment] = await connection.query<RowDataPacket[]>(
      `SELECT 
        fsbs.id, 
        fsbs.status,
        fsbs.meeting_link as current_meeting_link,
        fsbs.session_date,
        fsbs.start_time,
        fsbs.end_time,
        s.id as student_id,
        s.first_name as student_name, 
        s.email as student_email,
        s.phone as student_phone
      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, headers: corsHeaders }
      );
    }

    const appointmentData = appointment[0];
    
    // Check if appointment is confirmed or scheduled (only then meeting link can be added)
    const allowedStatuses = ['confirmed', 'scheduled'];
    if (!allowedStatuses.includes(appointmentData.status)) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: `Meeting link can only be added for confirmed or scheduled appointments. Current status: ${appointmentData.status}` 
        },
        { status: 400, headers: corsHeaders }
      );
    }

    // Check if meeting date and time has passed
    const currentDateTime = new Date();
    const meetingDateTime = new Date(`${appointmentData.session_date}T${appointmentData.start_time}`);
    
    if (currentDateTime > meetingDateTime) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Cannot share meeting link for past appointments. The meeting time has already passed.' 
        },
        { status: 400, headers: corsHeaders }
      );
    }

    // Check if meeting is within reasonable time (not more than 24 hours before)
    const hoursBeforeMeeting = (meetingDateTime.getTime() - currentDateTime.getTime()) / (1000 * 60 * 60);
    if (hoursBeforeMeeting > 24) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Meeting link can only be shared within 24 hours before the scheduled meeting time.' 
        },
        { status: 400, headers: corsHeaders }
      );
    }

    // 2. Update meeting link
    const [updateResult] = await connection.query<ResultSetHeader>(
      `UPDATE foreign_student_booked_sessions 
       SET meeting_link = ?, updated_at = NOW()
       WHERE id = ? AND foreign_student_id = ?`,
      [validatedData.meeting_link, appointmentId, foreignStudentId]
    );

    if (updateResult.affectedRows === 0) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Failed to update meeting link' },
        { status: 500, headers: corsHeaders }
      );
    }

    // Commit transaction
    await connection.commit();

    // Fetch updated appointment data
    const [updatedAppointment] = await connection.query<RowDataPacket[]>(
      `SELECT 
        fsbs.id,
        fsbs.status,
        fsbs.meeting_link,
        fsbs.session_date,
        fsbs.start_time,
        fsbs.end_time,
        fsbs.amount,
        s.first_name as student_name,
        s.email as student_email
      FROM foreign_student_booked_sessions fsbs
      INNER JOIN users s ON fsbs.student_id = s.id
      WHERE fsbs.id = ?`,
      [appointmentId]
    );

    connection.release();

    // Format response times
    const formatDateTime = (date: string, time: string) => {
      return new Date(`${date}T${time}`).toLocaleString();
    };

    return NextResponse.json({
      success: true,
      message: 'Meeting link updated and sent to student successfully',
      data: {
        appointment_id: appointmentId,
        meeting_link: validatedData.meeting_link,
        previous_link: appointmentData.current_meeting_link || null,
        appointment: {
          ...updatedAppointment[0],
          meeting_time: formatDateTime(appointmentData.session_date, appointmentData.start_time),
          meeting_link_sent_at: new Date().toISOString()
        }
      }
    }, { status: 200, headers: corsHeaders });

  } catch (err: any) {
    // Rollback on any error
    if (connection) {
      await connection.rollback();
      connection.release();
    }
    
    console.error('Update meeting link error:', err);
    
    // Zod validation errors
    if (err instanceof z.ZodError) {
      const errors = {};
      err.errors.forEach(error => {
        const path = error.path.join('.');
        errors[path] = error.message;
      });
      
      return NextResponse.json(
        { 
          success: false, 
          message: 'Validation failed', 
          errors 
        },
        { status: 400, headers: corsHeaders }
      );
    }
    
    // Database or other errors
    return NextResponse.json(
      { 
        success: false, 
        message: err.message || 'Failed to update meeting link' 
      },
      { status: 500, headers: corsHeaders }
    );
  }
}