import { RowDataPacket } from "mysql2";
import pool from "../../../../../lib/db/db";
import { NextResponse } from "next/server";

const connection = await pool.getConnection();

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

export async function PATCH(request, { params }: PageProps) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { status } = body;

    if (status === undefined) {
      return NextResponse.json(
        { success: false, error: "Status is required" },
        { status: 400 }
      );
    }
    
    try {
      await connection.query(
        "UPDATE scholarships_comments SET is_approved = ? WHERE id = ?",
        [status ? 1 : 0, id]
      );

      return NextResponse.json({
        success: true,
        message: `Comment ${status ? "approved" : "set to pending"} successfully`
      });
    } finally {
      connection.release();
    }
  } catch (err) {
    console.error("❌ PATCH Scholarship Comment API Error:", err);
    return NextResponse.json(
      {
        success: false,
        error: "Failed to update comment status",
        details: err.message,
      },
      { status: 500 }
    );
  }
}

export async function DELETE(request, { params }: PageProps) {
  try {
    const { id } = await params;
    
    try {
      await connection.query("DELETE FROM scholarships_comments WHERE id = ?", [id]);

      return NextResponse.json({
        success: true,
        message: "Comment deleted successfully"
      });
    } finally {
      connection.release();
    }
  } catch (err) {
    console.error("❌ DELETE Scholarship Comment API Error:", err);
    return NextResponse.json(
      {
        success: false,
        error: "Failed to delete comment",
        details: err.message,
      },
      { status: 500 }
    );
  }
}