import { api } from "./client";

export interface ConverterCapabilities {
  imageConverter: boolean;
  audioVideoConverter: boolean;
  docConverter: boolean;
  dataConverter: boolean;
}

export interface ConvertJobResult {
  jobId: string;
  status: string;
}

export interface ConvertMimeError {
  error: string;
  actualMime: string;
  claimedMime: string;
}

export async function submitConvertJob(
  companyId: string,
  file: File,
  targetFormat: string,
): Promise<ConvertJobResult | ConvertMimeError> {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("targetFormat", targetFormat);

  // Use fetch directly so we can inspect 422 vs 202 status codes before throwing
  const res = await fetch(`/api/companies/${companyId}/convert`, {
    method: "POST",
    body: formData,
    credentials: "include",
    // Do NOT set Content-Type — browser sets multipart boundary automatically
  });

  if (res.status === 422) {
    return (await res.json()) as ConvertMimeError;
  }

  if (res.status === 202) {
    return (await res.json()) as ConvertJobResult;
  }

  const errorBody = await res.json().catch(() => null);
  const message =
    (errorBody as { error?: string } | null)?.error ?? `Request failed: ${res.status}`;
  throw new Error(message);
}

export async function getConverterCapabilities(): Promise<ConverterCapabilities> {
  return api.get<ConverterCapabilities>("/system/converters");
}
