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

// TODO: replace with the actual id of the Contact Us row in cms_pages
const CONTACT_PAGE_ID = BigInt(8);

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

// GET: fetch the single Contact entry (always scoped to Contact Us 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_contact.findUnique({
      where: { page_id: CONTACT_PAGE_ID },
    });

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

// POST: create the Contact entry (only if one doesn't exist yet)
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 pageExists = await prisma.cms_pages.findUnique({
      where: { id: CONTACT_PAGE_ID },
    });

    if (!pageExists) {
      return NextResponse.json(
        { success: false, message: "Contact Us page does not exist in cms_pages" },
        { status: 400 }
      );
    }

    const existing = await prisma.cms_contact.findUnique({
      where: { page_id: CONTACT_PAGE_ID },
    });

    if (existing) {
      return NextResponse.json(
        {
          success: false,
          message: "A Contact entry already exists. Please edit it instead.",
        },
        { status: 400 }
      );
    }

    const section_name = String(body.section_name || "").trim();

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

    const item = await prisma.cms_contact.create({
      data: {
        page_id: CONTACT_PAGE_ID,
        section_name,
        html_content: String(body.html_content || ""),
        in_person_heading: String(body.in_person_heading || "In-Person"),
        in_person_content: String(body.in_person_content || ""),
        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 the existing Contact entry
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.findUnique({
      where: { id },
    });

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

    const section_name = String(body.section_name || "").trim();

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

    const item = await prisma.cms_contact.update({
      where: { id },
      data: {
        section_name,
        html_content: String(body.html_content || ""),
        in_person_heading: String(body.in_person_heading || "In-Person"),
        in_person_content: String(body.in_person_content || ""),
        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 }
    );
  }
}