/**
 * GET /api/site-tag/schema?domain=X&page=/path — Public endpoint.
 * Returns auto-inject schemas for a domain+page. Called by Site Tag script.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCorsHeaders } from "@/lib/services/page-lifecycle";

export const dynamic = "force-dynamic";

export async function OPTIONS(req: Request) {
  return new NextResponse(null, { status: 204, headers: getCorsHeaders(req) });
}

export async function GET(req: Request) {
  const cors = getCorsHeaders(req);
  const url = new URL(req.url);
  const domain = url.searchParams.get("domain");
  const page = url.searchParams.get("page");

  if (!domain) return NextResponse.json({ schemas: [] }, { headers: cors });

  // Find brand by domain
  const brand = await prisma.brand.findFirst({
    where: { domain: { contains: domain.replace(/^www\./, "") } },
    select: { id: true },
  });
  if (!brand) return NextResponse.json({ schemas: [] }, { headers: cors });

  const where: { brandId: string; autoInject: boolean; pageUrl?: string } = {
    brandId: brand.id,
    autoInject: true,
  };

  // If page specified, find schemas for that specific page or site-wide schemas
  if (page) {
    const schemas = await prisma.schemaMarkup.findMany({
      where: { brandId: brand.id, autoInject: true, pageUrl: { in: [page, "/", "*"] } },
      select: { schemaType: true, jsonLd: true },
    });
    return NextResponse.json({ schemas: schemas.map((s: { jsonLd: unknown }) => s.jsonLd) }, { headers: cors });
  }

  const schemas = await prisma.schemaMarkup.findMany({
    where,
    select: { schemaType: true, jsonLd: true },
  });

  return NextResponse.json({ schemas: schemas.map((s: { jsonLd: unknown }) => s.jsonLd) }, { headers: cors });
}
