import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { NextResponse } from "next/server";

const KUCHIPUDI_EXAMS_PAGE_ID = BigInt(6);

const serializeBigInt = (data: any) =>
  JSON.parse(
    JSON.stringify(data, (_, value) =>
      typeof value === "bigint" ? value.toString() : value
    )
  );

// GET: list all certified students for this page
export async function GET() {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      { success: false, message: "Unauthorized" },
      { status: 401 }
    );
  }

  try {
    const data = await prisma.cms_certified_students.findMany({
      where: { page_id: KUCHIPUDI_EXAMS_PAGE_ID },
      orderBy: [{ level_name: "desc" }, { sort_order: "asc" }, { id: "asc" }],
    });

    return NextResponse.json({ success: true, data: serializeBigInt(data) });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: error.message || "Failed to fetch data" },
      { status: 500 }
    );
  }
}

// POST: add a certified student
export async function POST(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      { success: false, message: "Unauthorized" },
      { status: 401 }
    );
  }

  try {
    const body = await req.json();

    const level_name = String(body.level_name || "").trim();
    const student_name = String(body.student_name || "").trim();

    if (!level_name || !student_name) {
      return NextResponse.json(
        { success: false, message: "Level and student name are required" },
        { status: 400 }
      );
    }

    const item = await prisma.cms_certified_students.create({
      data: {
        page_id: KUCHIPUDI_EXAMS_PAGE_ID,
        level_name,
        student_name,
        image: body.image ? String(body.image) : null,
        sort_order: Number(body.sort_order) || 0,
        status: Boolean(body.status),
      },
    });

    return NextResponse.json({ success: true, data: serializeBigInt(item) });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: error.message || "Failed to create record" },
      { status: 500 }
    );
  }
}

// PUT: update a certified student
export async function PUT(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      { success: false, message: "Unauthorized" },
      { status: 401 }
    );
  }

  try {
    const body = await req.json();
    const id = BigInt(String(body.id));

    const existing = await prisma.cms_certified_students.findUnique({ where: { id } });

    if (!existing) {
      return NextResponse.json(
        { success: false, message: "Record not found" },
        { status: 404 }
      );
    }

    const level_name = String(body.level_name || "").trim();
    const student_name = String(body.student_name || "").trim();

    if (!level_name || !student_name) {
      return NextResponse.json(
        { success: false, message: "Level and student name are required" },
        { status: 400 }
      );
    }

    const item = await prisma.cms_certified_students.update({
      where: { id },
      data: {
        level_name,
        student_name,
        image: body.image ? String(body.image) : null,
        sort_order: Number(body.sort_order) || 0,
        status: Boolean(body.status),
        updated_at: new Date(),
      },
    });

    return NextResponse.json({ success: true, data: serializeBigInt(item) });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: error.message || "Failed to update record" },
      { status: 500 }
    );
  }
}

// DELETE: remove a certified student (?id=)
export async function DELETE(req: Request) {
  const admin = await getAdminUser();

  if (!admin) {
    return NextResponse.json(
      { success: false, message: "Unauthorized" },
      { status: 401 }
    );
  }

  try {
    const { searchParams } = new URL(req.url);
    const idParam = searchParams.get("id");

    if (!idParam) {
      return NextResponse.json(
        { success: false, message: "id is required" },
        { status: 400 }
      );
    }

    await prisma.cms_certified_students.delete({
      where: { id: BigInt(idParam) },
    });

    return NextResponse.json({ success: true });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: error.message || "Failed to delete record" },
      { status: 500 }
    );
  }
}