/**
 * Server-side client for the current user's render jobs + finished exports.
 * Calls the gateway with the caller's Identity access JWT (fr_access cookie).
 */
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";

export interface MyRenderJob {
  id: string;
  step: string;
  render_progress?: number | null;
  title?: string | null;
  name?: string | null;
  project_name?: string | null;
  quality?: string | null;
  resolution?: string | null;
  image_preview_b64?: string | null;
  export_id?: string | null;
  failed_message?: string | null;
  created_at: string;
}

export interface MyExport {
  id: string;
  image?: string | null;
  file_type?: string | null;
  file_extension?: string | null;
  render_quality?: string | null;
  size_bytes?: number | null;
  duration_sec?: number | null;
  width?: number | null;
  height?: number | null;
  produce_date?: string | null;
  auto_delete_date?: string | null;
}

async function getJSON(path: string): Promise<{ data?: unknown[] } | null> {
  const token = await getAccessToken();
  if (!token) return null;
  try {
    const res = await fetch(gatewayUrl(path), {
      headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
      cache: "no-store",
    });
    if (!res.ok) return null;
    return (await res.json()) as { data?: unknown[] };
  } catch {
    return null;
  }
}

export async function listMyRenders(): Promise<MyRenderJob[]> {
  const d = await getJSON("/v1/renders?page=1&page_size=50");
  return (d?.data as MyRenderJob[]) ?? [];
}

export async function listMyExports(): Promise<MyExport[]> {
  const d = await getJSON("/v1/exports?page=1&page_size=50");
  return (d?.data as MyExport[]) ?? [];
}

/** Steps that mean the job is still running. */
export const ACTIVE_STEPS = new Set([
  "Queued", "Preparing", "TemplateCache", "JsxGen", "Music", "Rendering",
  "Validating", "Repairing", "Optimisation", "Video", "Mixing", "Final", "Uploading",
]);
