import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { detectSnippet } from "@/lib/services/snippet-detector";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

export async function POST(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { brandId, domain: rawDomain } = await req.json();

  let domain: string;

  if (rawDomain) {
    domain = rawDomain;
  } else if (brandId) {
    const brand = await prisma.brand.findUnique({
      where: { id: brandId },
      select: { id: true, name: true, domain: true },
    });
    if (!brand) {
      return NextResponse.json({ error: "Brand not found" }, { status: 404 });
    }
    if (!brand.domain) {
      return NextResponse.json({ error: "Brand has no domain configured" }, { status: 400 });
    }
    domain = brand.domain;
  } else {
    return NextResponse.json({ error: "brandId or domain required" }, { status: 400 });
  }

  const result = await detectSnippet(domain);

  return NextResponse.json({
    domain,
    ...result,
  });
}
