import { config } from "../config.js";

export type RenderJobPatch = {
  status?: "queued" | "processing" | "ready" | "failed";
  progress_pct?: number;
  worker_id?: string;
  output_path?: string;
  thumbnail_path?: string;
  duration_seconds?: number;
  error_message?: string;
};

export type QueuedRenderJob = {
  uuid: string;
  template_slug: string;
  created_at: string | null;
};

export class LaravelClient {
  constructor(
    private readonly baseUrl = config.apiUrl,
    private readonly token = config.apiToken,
  ) {}

  async fetchQueuedJobs(): Promise<QueuedRenderJob[]> {
    const response = await this.request<{ render_jobs: QueuedRenderJob[] }>(
      "/api/v1/render-jobs/queued",
    );

    return response.render_jobs;
  }

  async fetchManifest(renderJobUuid: string): Promise<unknown> {
    return this.request(`/api/v1/render-jobs/${renderJobUuid}/manifest`);
  }

  async patchRenderJob(renderJobUuid: string, body: RenderJobPatch): Promise<void> {
    await this.request(`/api/v1/render-jobs/${renderJobUuid}`, {
      method: "PATCH",
      body: JSON.stringify(body),
    });
  }

  private async request<T = unknown>(
    path: string,
    init: RequestInit = {},
  ): Promise<T> {
    const response = await fetch(`${this.baseUrl}${path}`, {
      ...init,
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${this.token}`,
        "Content-Type": "application/json",
        ...(init.headers ?? {}),
      },
    });

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`Colibri API ${init.method ?? "GET"} ${path} failed (${response.status}): ${text}`);
    }

    if (response.status === 204) {
      return undefined as T;
    }

    return (await response.json()) as T;
  }
}
