/**
 * POST /api/admin/extract-services
 * ----------------------------------
 * Superadmin-only endpoint for manually testing extractBrandServices().
 * Runs the Claude-powered extraction against a brand's website and
 * returns the result. Safe to call repeatedly — dry-run by default.
 *
 * Body:
 *   { brandId: string, dryRun?: boolean }
 *   dryRun defaults to true — pass dryRun: false to actually write.
 */

import { NextResponse } from "next/server";
import { requireSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { extractBrandServices } from "@/lib/services/brand-extract";

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

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

  const body = await req.json().catch(() => ({}));
  const brandId = body.brandId as string | undefined;
  const dryRun: boolean = body.dryRun !== false; // default true

  if (!brandId) {
    return NextResponse.json({ error: "brandId required" }, { status: 400 });
  }

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

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

  const result = await extractBrandServices(brand.domain);

  if (!result) {
    return NextResponse.json(
      {
        error: "Extraction failed or returned no services",
        brand: { id: brand.id, name: brand.name, domain: brand.domain },
      },
      { status: 500 },
    );
  }

  if (dryRun) {
    return NextResponse.json({
      dryRun: true,
      brand: { id: brand.id, name: brand.name, domain: brand.domain },
      current: {
        primaryServices: brand.primaryServices,
        secondaryServices: brand.secondaryServices,
      },
      extracted: result,
    });
  }

  await prisma.brand.update({
    where: { id: brandId },
    data: {
      primaryServices: result.primaryServices,
      secondaryServices: result.secondaryServices,
    },
  });

  return NextResponse.json({
    dryRun: false,
    brand: { id: brand.id, name: brand.name, domain: brand.domain },
    saved: result,
  });
}
