import { request, BASE, ApiError } from "./client";

// ── Types ────────────────────────────────────────────────────────────────────

export interface GeneratedShort {
  id: string;
  highlight_candidate_id: string;
  format_preset: "vertical" | "square" | "horizontal";
  status: "pending" | "processing" | "complete" | "failed";
  error_message: string | null;
  file_size_bytes: number | null;
  duration_secs: number | null;
  width: number;
  height: number;
  created_at: string;
  share_token: string | null;
}

export interface PublicShortResponse {
  format_preset: string;
  width: number;
  height: number;
  duration_secs: number | null;
  creator_name: string;
  highlight_title: string;
  download_url: string;
}

export interface ShortsListResponse {
  shorts: GeneratedShort[];
}

export interface GenerateResponse {
  status: string;
  message: string;
}

export interface DownloadResponse {
  download_url: string;
  format_preset: string;
}

// ── API functions ────────────────────────────────────────────────────────────

export function generateShorts(
  highlightId: string,
  captions: boolean = true,
): Promise<GenerateResponse> {
  const params = captions ? "" : "?captions=false";
  return request<GenerateResponse>(
    `${BASE}/admin/shorts/generate/${encodeURIComponent(highlightId)}${params}`,
    { method: "POST" },
  );
}

export function fetchShorts(highlightId: string): Promise<ShortsListResponse> {
  return request<ShortsListResponse>(
    `${BASE}/admin/shorts/${encodeURIComponent(highlightId)}`,
  );
}

export function getShortDownloadUrl(
  shortId: string,
): Promise<DownloadResponse> {
  return request<DownloadResponse>(
    `${BASE}/admin/shorts/download/${encodeURIComponent(shortId)}`,
  );
}

/**
 * Fetch a public short by share token — no auth required.
 * Uses raw fetch instead of `request()` to avoid injecting the auth header.
 */
export async function fetchPublicShort(
  token: string,
): Promise<PublicShortResponse> {
  const res = await fetch(
    `${BASE}/public/shorts/${encodeURIComponent(token)}`,
  );
  if (!res.ok) {
    const detail = res.status === 404 ? "Short not found" : res.statusText;
    throw new ApiError(res.status, detail);
  }
  return res.json() as Promise<PublicShortResponse>;
}
