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;
  const data = await request.json();

  try {
    // Process show_in_menu field value
    const showInMenuValue = data.show_in_menu === 'true' || data.show_in_menu === true;

    // Update only the show_in_menu field
    const query = 'UPDATE courses SET show_in_menu = ? WHERE id = ?';
    const queryParams = [showInMenuValue, parseInt(id)];

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

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { error: 'Course not found' },
        { status: 404 }
      );
    }

    // Get the updated course data
    const [updatedCourse] = await pool.query<RowDataPacket[]>(
      "SELECT id, name, show_in_menu FROM courses WHERE id = ?",
      [parseInt(id)]
    );

    // Log the activity
    await pool.query(
      "INSERT INTO activity_logs (user_id, action) VALUES (?, ?)", 
      [decoded.id, `Course ${updatedCourse[0].name} menu visibility toggled to ${showInMenuValue ? 'ON' : 'OFF'} by user ${decoded.name}`]
    );

    return Response.json({
      success: true,
      data: updatedCourse[0],
      message: `Menu visibility ${showInMenuValue ? 'enabled' : 'disabled'} successfully`
    }, { status: 200 });

  } catch (error) {
    console.error('Error updating menu visibility:', error);
    return Response.json(
      { error: 'Failed to update menu visibility', details: error.message },
      { status: 500 }
    );
  }
}