import { NextResponse } from "next/server";

import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";

export const dynamic = "force-dynamic";

export interface ActiveRender {
  id: string;
  saved_project_id: string;
  name: string | null;
  step: string;
  render_progress: number;
  preview_b64: string | null;
  created_at: string;
}

export interface ActiveRendersResponse {
  active: ActiveRender[];
  max_renders: number;
  can_start_new: boolean;
}

/**
 * The user's in-flight renders + their concurrent-render ceiling. Powers the
 * app-wide mini progress widget and the "can I start another render?" gate.
 * Returns an empty set (not 401) when signed out, so the widget can mount globally.
 */
export async function GET() {
  const token = await getAccessToken();
  const empty: ActiveRendersResponse = { active: [], max_renders: 1, can_start_new: true };
  if (!token) return NextResponse.json(empty);

  const res = await fetch(gatewayUrl("/v1/renders/active"), {
    cache: "no-store",
    headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
  });
  if (!res.ok) return NextResponse.json(empty);

  const data = (await res.json().catch(() => null)) as ActiveRendersResponse | null;
  return NextResponse.json(data ?? empty);
}
