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

const CONTACT_PAGE_ID = BigInt(8);

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

// GET: list all studios for the Contact page, ordered by sort_order
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_contact_studios.findMany({
      where: { page_id: CONTACT_PAGE_ID },
      orderBy: { sort_order: "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 new studio
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 studio_name = String(body.studio_name || "").trim();
    const address = String(body.address || "").trim();

    if (!studio_name || !address) {
      return NextResponse.json(
        { success: false, message: "Studio name and address are required" },
        { status: 400 }
      );
    }

    const maxOrder = await prisma.cms_contact_studios.aggregate({
      where: { page_id: CONTACT_PAGE_ID },
      _max: { sort_order: true },
    });

    const item = await prisma.cms_contact_studios.create({
      data: {
        page_id: CONTACT_PAGE_ID,
        studio_name,
        address,
        address_map_url: String(body.address_map_url || ""),
        map_embed_url: String(body.map_embed_url || ""),
        email: String(body.email || ""),
        phone: String(body.phone || ""),
        sort_order: (maxOrder._max.sort_order ?? 0) + 1,
        status: body.status !== undefined ? Boolean(body.status) : true,
      },
    });

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

// PUT: update an existing studio
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_contact_studios.findUnique({ where: { id } });

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

    const studio_name = String(body.studio_name || "").trim();
    const address = String(body.address || "").trim();

    if (!studio_name || !address) {
      return NextResponse.json(
        { success: false, message: "Studio name and address are required" },
        { status: 400 }
      );
    }

    const item = await prisma.cms_contact_studios.update({
      where: { id },
      data: {
        studio_name,
        address,
        address_map_url: String(body.address_map_url || ""),
        map_embed_url: String(body.map_embed_url || ""),
        email: String(body.email || ""),
        phone: String(body.phone || ""),
        status: body.status !== undefined ? Boolean(body.status) : existing.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 studio" },
      { status: 500 }
    );
  }
}

// DELETE: remove a studio (?id=123)
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 }
      );
    }

    const id = BigInt(idParam);

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

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

    await prisma.cms_contact_studios.delete({ where: { id } });

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