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

export async function PUT(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  try {
    const { id: rawId } = await params;
    const id = parseInt(rawId);
    const body = await req.json();

    if (!body.title?.trim())
      return NextResponse.json({ success: false, message: "Title is required" }, { status: 400 });

    const existing = await prisma.cms_marquee.findUnique({ where: { id } });
    if (!existing)
      return NextResponse.json({ success: false, message: "Marquee not found" }, { status: 404 });

    const marquee = await prisma.cms_marquee.update({
      where: { id },
      data: {
        title: body.title.trim(),
        link: body.link?.trim() || null,
        highlight: body.highlight ?? existing.highlight,
        status: body.status ?? existing.status,
        updated_at: new Date(),
      },
    });

    return NextResponse.json({ success: true, data: marquee });
  } catch (err) {
    console.error("Update Marquee error:", err);
    return NextResponse.json({ success: false, message: "Failed to update marquee" }, { status: 500 });
  }
}

export async function DELETE(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ success: false }, { status: 401 });

  try {
    const { id: rawId } = await params;
    const id = parseInt(rawId);

    const existing = await prisma.cms_marquee.findUnique({ where: { id } });
    if (!existing)
      return NextResponse.json({ success: false, message: "Marquee not found" }, { status: 404 });

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

    return NextResponse.json({ success: true, message: "Marquee deleted successfully" });
  } catch (err) {
    console.error("Delete Marquee error:", err);
    return NextResponse.json({ success: false, message: "Failed to delete marquee" }, { status: 500 });
  }
}