/**
 * POST /api/schema/generate-for-brief
 *
 * Generates JSON-LD schema markup scaffolded off a Content Brief
 * (SEO or LLMO). Distinct from /api/schema/generate in two ways:
 *
 *   1. No published pageUrl required — the user is PLANNING the
 *      page, not auditing one that exists. The generator takes
 *      brief fields (title, description, keyword, type, mode)
 *      instead of fetching a live HTML doc.
 *   2. LLMO vs SEO path. Each flavour gets a different system
 *      prompt bias — LLMO favours citation-optimised schema
 *      (Article/MedicalWebPage with SpeakableSpec, full author +
 *      date metadata); SEO favours Google-rich-results friendly
 *      schema (BlogPosting, Article with article thumbnails).
 *
 * No persistence. The user copies the returned JSON-LD to their
 * clipboard + pastes it into their CMS / page head manually. If
 * they want to save it for later, the Schema Generator page
 * already offers that for published URLs — this endpoint is
 * specifically for the brief → schema inline workflow.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { generateBriefSchema, type BriefSchemaInput } from "@/lib/services/schema-generator";

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

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

  const body = await req.json().catch(() => null) as {
    brandId?: string;
    briefType?: "seo" | "llmo";
    title?: string;
    description?: string;
    keyword?: string;
    secondaryKeywords?: string[];
    mode?: "standard" | "humanized";
    forceSchemaType?: string;
    contentSignal?: string;
  } | null;

  const brandId = body?.brandId;
  const briefType = body?.briefType;
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  if (briefType !== "seo" && briefType !== "llmo") {
    return NextResponse.json({ error: "briefType must be 'seo' or 'llmo'" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const input: BriefSchemaInput = {
    briefType,
    title: body?.title,
    description: body?.description,
    keyword: body?.keyword,
    secondaryKeywords: Array.isArray(body?.secondaryKeywords) ? body.secondaryKeywords : undefined,
    mode: body?.mode === "humanized" ? "humanized" : "standard",
    forceSchemaType: body?.forceSchemaType,
    contentSignal: body?.contentSignal,
  };

  try {
    const result = await generateBriefSchema(brandId, input);
    return NextResponse.json(result);
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Generation failed";
    console.error("[schema:generate-for-brief] failed", { brandId, briefType, err: msg });
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
