import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2/promise';

export async function POST(request: NextRequest) {
  const connection = await pool.getConnection();

  try {

    const authHeader = request.headers.get('authorization');
    const expectedApiKey = `Bearer ${process.env.CRM_API_KEY}`;

    if (!authHeader || authHeader !== expectedApiKey) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized: Invalid API key' },
        { status: 401 }
      );
    }

    const body = await request.json();
    const { foreign_student_id, status } = body;

    if (!foreign_student_id) {
      return NextResponse.json(
        { success: false, message: 'Foreign Student ID is required' },
        { status: 400 }
      );
    }

    if (![0, 1].includes(status)) {
      return NextResponse.json(
        { success: false, message: "Status must be '0' or '1'" },
        { status: 400 }
      );
    }

    const [updateResult] = await connection.query<ResultSetHeader>(
      `
      UPDATE foreign_students
      SET is_active = ?
      WHERE id = ?
      `,
      [status, foreign_student_id]
    );

    
    if (updateResult.affectedRows === 0) {
      return NextResponse.json(
        { success: false, message: 'Failed to update Foreign Student Status' },
        { status: 500 }
      );
    }

    const [updatedForeignStudent] = await connection.query<RowDataPacket[]>(
      `
      SELECT id, name, email, phone FROM foreign_students WHERE id = ?
      `,
      [foreign_student_id]
    );

    const responseMessage = status === 1 ? 'Foreign Student Activated Successfully.' : 'Foreign Studend Deactivated Successfully.';

    return NextResponse.json(
      {
        success: true,
        message: responseMessage,
        data: updatedForeignStudent,
      },
      { status: 200 }
    );
  } catch (error: any) {

    console.error('CRM Approval API error:', error);

    return NextResponse.json(
      { success: false, message: error.message || 'Internal server error' },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}
