/**
 * POST /api/schema/generate — AI-powered schema markup generation.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { generateSchema } from "@/lib/services/schema-generator";
import { trackEvent } from "@/lib/services/platform-telemetry";

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);
  const brandId = body?.brandId as string;
  const pageUrl = body?.pageUrl as string;
  const schemaType = body?.schemaType as string | undefined;

  if (!brandId || !pageUrl) return NextResponse.json({ error: "brandId and pageUrl required" }, { 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 });
  }

  try {
    const result = await generateSchema(brandId, pageUrl, schemaType);
    // Engagement telemetry — fire-and-forget after the main work is done.
    trackEvent({
      userId: user.id,
      brandId,
      action: "generate_schema",
      category: "technical",
      metadata: { pageUrl, schemaType: schemaType ?? null },
      request: req,
    });
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Generation failed" }, { status: 500 });
  }
}
