import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

// id of the cms_pages row that class levels belong to.
// Update this to match the actual Academy page's id in your cms_pages table.
const PAGE_ID = BigInt(3);

// Convert BigInt -> string so JSON.stringify doesn't blow up
function serialize<T>(data: T): T {
  return JSON.parse(
    JSON.stringify(data, (_, value) =>
      typeof value === "bigint" ? value.toString() : value
    )
  );
}

async function getPageId() {
  const page = await prisma.cms_pages.findUnique({
    where: { id: PAGE_ID },
    select: { id: true },
  });

  if (!page) {
    throw new Error(
      `cms_pages row with id "${PAGE_ID}" not found. Create it first (or update PAGE_ID in this route).`
    );
  }

  return page.id;
}

// GET: fetch all class levels (admin view -> includes inactive), ordered by sort_order
export async function GET() {
  try {
    const pageId = await getPageId();

    const classLevels = await prisma.cms_class_levels.findMany({
      where: { page_id: pageId },
      orderBy: { sort_order: "asc" },
    });

    return NextResponse.json(
      { success: true, data: serialize(classLevels) },
      { status: 200, headers: { "Cache-Control": "no-store" } }
    );
  } catch (error) {
    console.error("Error fetching Class Levels:", error);

    return NextResponse.json(
      {
        success: false,
        message: "Failed to fetch Class Levels data",
        error: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

// POST: create a new class level card
export async function POST(req: NextRequest) {
  try {
    const pageId = await getPageId();
    const body = await req.json();

    const created = await prisma.cms_class_levels.create({
      data: {
        page_id: pageId,
        title: body.title ?? "",
        age: body.age ?? null,
        duration: body.duration ?? null,
        prerequisite: body.prerequisite ?? null,
        description: body.description ?? null,
        points: body.points ?? null,
        sort_order: body.sort_order ?? 0,
        status: body.status ?? true,
      },
    });

    return NextResponse.json(
      { success: true, data: serialize(created) },
      { status: 201 }
    );
  } catch (error) {
    console.error("Error creating Class Level:", error);

    return NextResponse.json(
      {
        success: false,
        message: "Failed to create Class Level",
        error: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

// PUT: update an existing class level card
export async function PUT(req: NextRequest) {
  try {
    const body = await req.json();

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

    const updated = await prisma.cms_class_levels.update({
      where: { id: BigInt(body.id) },
      data: {
        title: body.title,
        age: body.age,
        duration: body.duration,
        prerequisite: body.prerequisite,
        description: body.description,
        points: body.points,
        sort_order: body.sort_order,
        status: body.status,
        updated_at: new Date(),
      },
    });

    return NextResponse.json(
      { success: true, data: serialize(updated) },
      { status: 200 }
    );
  } catch (error) {
    console.error("Error updating Class Level:", error);

    return NextResponse.json(
      {
        success: false,
        message: "Failed to update Class Level",
        error: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

// DELETE: remove a class level card  (expects ?id=123)
export async function DELETE(req: NextRequest) {
  try {
    const id = req.nextUrl.searchParams.get("id");

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

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

    return NextResponse.json({ success: true }, { status: 200 });
  } catch (error) {
    console.error("Error deleting Class Level:", error);

    return NextResponse.json(
      {
        success: false,
        message: "Failed to delete Class Level",
        error: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}