// app/api/internal/university/[id]/active/route.js
import { verifyAuthentication } from "../../../../../utils/verifyAuthentication";
import { NextRequest, NextResponse } from "next/server";
import pool from "../../../../../../lib/db/db";
import { ResultSetHeader, RowDataPacket } from "mysql2";

export async function PATCH(request: NextRequest, { params }) {
  const token = request.cookies.get("university-token")?.value || null;

  if (!token) {
    return NextResponse.json(
      {
        message: "Please Login to continue"
      },
      {
        status: 400
      }
    );
  }

  const decoded = await verifyAuthentication(token);

  if (decoded instanceof NextResponse) {
    return NextResponse.json(
      {
        message: "You are not authorized to do this action"
      },
      {
        status: 400
      }
    );
  }

  const { id } = await params;
  
  if (!id || isNaN(parseInt(id))) {
    return NextResponse.json(
      { error: 'Invalid university ID' },
      { status: 400 }
    );
  }

  try {
    const data = await request.json();
    
    // Validate request body
    if (data.is_active === undefined) {
      return NextResponse.json(
        { error: 'is_active field is required in request body' },
        { status: 400 }
      );
    }

    // Process is_active field value
    const isActiveValue = data.is_active === true || data.is_active === 'true' || data.is_active === 1;

    console.log(`🔄 Updating university ${id} active status to: ${isActiveValue}`);

    // Get current university data first
    const [currentUniversityRows] = await pool.query<RowDataPacket[]>(
      "SELECT * FROM university_details WHERE id = ?",
      [parseInt(id)]
    );

    if (currentUniversityRows.length === 0) {
      return NextResponse.json(
        { error: 'University not found' },
        { status: 404 }
      );
    }

    const currentUniversity = currentUniversityRows[0];

    // Update MySQL database only
    const query = 'UPDATE university_details SET is_active = ? WHERE id = ?';
    const queryParams = [isActiveValue, parseInt(id)];

    const [result] = await pool.execute<ResultSetHeader>(query, queryParams);

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { error: 'Failed to update university active status' },
        { status: 500 }
      );
    }

    // Get the updated university data
    const [updatedUniversityRows] = await pool.query<RowDataPacket[]>(
      "SELECT * FROM university_details WHERE id = ?",
      [parseInt(id)]
    );

    const updatedUniversity = updatedUniversityRows[0];

    // Log the activity
    await pool.query(
      "INSERT INTO activity_logs (user_id, action) VALUES (?, ?)", 
      [decoded.id, `University ${updatedUniversity.name} marked as ${isActiveValue ? 'active' : 'inactive'} by user ${decoded.name} (${decoded.email})`]
    );

    console.log(`✅ University ${id} active status updated to: ${isActiveValue}`);

    return NextResponse.json({
      success: true,
      data: updatedUniversity,
      message: `University ${isActiveValue ? 'activated' : 'deactivated'} successfully`
    }, { status: 200 });

  } catch (error) {
    console.error('Error updating university active status (PATCH):', error);
    return NextResponse.json(
      { 
        error: 'Internal server error',
        details: error.message 
      }, 
      { status: 500 }
    );
  }
}
