/**
 * POST /api/brands/extract
 * --------------------------
 * Extracts brand identity (logo, colors, font, industry) from a website.
 * Body: { brandId, domain }
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { extractBrandIdentity, saveExtractedBrand } from "@/lib/services/brand-extract";
import { log } from "@/lib/logger";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { brandId, domain } = await req.json();
  if (!brandId || !domain) {
    return NextResponse.json({ error: "brandId and domain required" }, { status: 400 });
  }

  log.info("api", `Brand extraction starting for ${domain}`, {
    path: "/api/brands/extract",
    metadata: { brandId, domain },
  });

  try {
    const extracted = await extractBrandIdentity(domain);
    await saveExtractedBrand(brandId, extracted);

    return NextResponse.json({
      ok: true,
      extracted,
    });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Extraction failed";
    log.error("api", `Brand extraction failed: ${msg}`, { metadata: { brandId, domain } });
    return NextResponse.json({ ok: false, error: msg }, { status: 500 });
  }
}
