import { NextResponse } from "next/server";
import { getSuperadmin, requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function POST(
  _req: Request,
  { params }: { params: { brandId: string } },
) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const brand = await prisma.brand.findUnique({
    where: { id: params.brandId },
    select: { id: true, name: true, status: true },
  });

  if (!brand) {
    return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  }

  if ((brand.status ?? "active").toLowerCase() !== "active") {
    return NextResponse.json({ brand, message: `Brand is already ${brand.status}`, changed: false });
  }

  const previousStatus = brand.status;

  const admin = await getSuperadmin().catch(() => null);
  const changedBy = admin?.email ?? "admin";

  const updated = await prisma.brand.update({
    where: { id: params.brandId },
    data: { status: "inactive", statusChangedAt: new Date(), statusChangedBy: changedBy },
    select: { id: true, name: true, status: true },
  });

  console.log("Brand deactivated", { brandId: params.brandId, previousStatus, newStatus: "inactive" });

  return NextResponse.json({ brand: updated, previousStatus, changed: true });
}
