import { NextResponse } from "next/server";

import { gatewayFetch } from "@/lib/api/gateway";

export const dynamic = "force-dynamic";

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

/**
 * Public list of PUBLISHED preset stories (premade example videos) for a content
 * project. No auth → the gateway/content-svc returns published stories only, which
 * is exactly what the template-detail "example videos" section needs.
 */
export async function GET(request: Request) {
  const projectId = new URL(request.url).searchParams.get("project_id") ?? "";
  if (!UUID_RE.test(projectId)) {
    return NextResponse.json({ stories: [] });
  }
  try {
    const res = await gatewayFetch(`/v1/preset-stories/?project_id=${projectId}`);
    if (!res.ok) return NextResponse.json({ stories: [] });
    const data = await res.json().catch(() => null);
    const stories = Array.isArray(data) ? data : (data?.data ?? []);
    return NextResponse.json({ stories });
  } catch {
    return NextResponse.json({ stories: [] });
  }
}
