// app/api/frontend/userdashboard/update-meeting-link/[id]/route.js
import pool from '../../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';
import { z } from 'zod';

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


// Validation schema
const meetingLinkSchema = z.object({
  meeting_link: z.string().url('Invalid URL format').max(500, 'Meeting link too long')
});

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

    const foreignStudentId = decoded.id;
    const body = await req.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, 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 = ? 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. Update meeting link
    await connection.query(
      `UPDATE foreign_student_booked_sessions 
       SET meeting_link = ?, updated_at = NOW()
       WHERE id = ? AND foreign_student_id = ?`,
      [validatedData.meeting_link, appointmentId, foreignStudentId]
    );

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

    return NextResponse.json({
      success: true,
      message: 'Meeting link updated successfully'
    }, { status: 200 });

  } 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 }
      );
    }
    
    // Database or other errors
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to update meeting link' 
      },
      { status: 500 }
    );
  }
}