import { ApiError, api, authedFetch } from "./api";

/** document = PDF (spec sheets, magazine, press kit), always served as a download. */
export type MediaKind = "image" | "video" | "document";
export type Media = {
  id: string;
  kind: MediaKind;
  mimeType: string;
  size: number;
  width: number | null;
  height: number | null;
  originalName: string;
  title: string | null;
  /** Unreliable: the API currently returns its internal host (http://localhost:4012/…). Use mediaUrl(). */
  url: string;
  /** e.g. /uploads/2026/11/<uuid>.webp, served by the API host. */
  path: string;
  uploadedBy: { id: string; email: string } | null;
  createdAt: string;
  updatedAt: string;
};
export type MediaQuery = { page: number; limit: number; search: string; kind: "" | MediaKind; sort: string };

/** Host that serves /uploads/*. Saved into content as an absolute URL so the website can load it. */
export const MEDIA_ORIGIN = (process.env.NEXT_PUBLIC_MEDIA_ORIGIN || "https://unionistbackend.sofrik.com").replace(/\/+$/, "");

/** The URL to store in content for a media item. */
export const mediaUrl = (m: Pick<Media, "path">) => `${MEDIA_ORIGIN}${m.path}`;

/* ------------------------------------------------------------------ */
/* Client-side checks (mirror the API's limits)                         */
/* ------------------------------------------------------------------ */

const MB = 1024 * 1024;
const IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif"];
const VIDEO_TYPES = ["video/mp4", "video/webm"];
const PDF = "application/pdf";
export const ACCEPT = {
  image: [...IMAGE_TYPES, "image/svg+xml"].join(","),
  video: VIDEO_TYPES.join(","),
  document: PDF,
  any: [...IMAGE_TYPES, "image/svg+xml", ...VIDEO_TYPES, PDF].join(","),
};

/** Problem with a file before uploading, or null. The server re-checks the real content. */
export function fileProblem(f: File, want: MediaKind | "any" = "any"): string | null {
  const isSvg = f.type === "image/svg+xml";
  const isImage = IMAGE_TYPES.includes(f.type) || isSvg;
  const isVideo = VIDEO_TYPES.includes(f.type);
  const isPdf = f.type === PDF || (!f.type && /\.pdf$/i.test(f.name));
  if (want === "image" && !isImage) return `${f.name}: use JPG, PNG, WebP, GIF, AVIF or SVG.`;
  if (want === "video" && !isVideo) return `${f.name}: use MP4 or WebM.`;
  if (want === "document" && !isPdf) return `${f.name}: use a PDF.`;
  if (!isImage && !isVideo && !isPdf) return `${f.name}: unsupported type. Images: JPG, PNG, WebP, GIF, AVIF, SVG. Video: MP4, WebM. Documents: PDF.`;
  if (isSvg && f.size > MB) return `${f.name}: SVG files can be at most 1 MB.`;
  if (isPdf && f.size > 20 * MB) return `${f.name}: PDFs can be at most 20 MB.`;
  if (!isPdf && f.size > 10 * MB) return `${f.name}: files can be at most 10 MB.`;
  return null;
}

/* ------------------------------------------------------------------ */
/* Endpoints                                                           */
/* ------------------------------------------------------------------ */

export async function uploadMedia(file: File, title?: string): Promise<Media> {
  const fd = new FormData();
  fd.append("file", file);
  const t = title?.trim().slice(0, 150);
  if (t) fd.append("title", t);
  let res = await authedFetch("/admin/media", { method: "POST", body: fd });
  // The API occasionally answers 500 to a valid upload; one retry usually succeeds.
  if (res.status >= 500) {
    await new Promise((r) => setTimeout(r, 800));
    res = await authedFetch("/admin/media", { method: "POST", body: fd });
  }
  if (!res.ok) {
    let msg = res.status === 413 ? "File too large." : res.status === 429 ? "Too many uploads. Wait a minute and try again." : res.statusText;
    let errors: string[] = [];
    try {
      const j = (await res.json()) as { message?: string; errors?: string[] };
      msg = j.message || msg;
      errors = j.errors ?? [];
    } catch {
      /* non-JSON error body */
    }
    throw new ApiError(res.status, msg, errors);
  }
  return ((await res.json()) as { data: Media }).data;
}

export const renameMedia = (id: string, title: string | null) => api<Media>(`/admin/media/${id}`, { method: "PATCH", body: { title } });
export const deleteMedia = (id: string) => api<void>(`/admin/media/${id}`, { method: "DELETE" });

/* ------------------------------------------------------------------ */
/* Display                                                             */
/* ------------------------------------------------------------------ */

export const prettySize = (n: number) => (n >= MB ? `${(n / MB).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
export const mediaName = (m: Media) => m.title || m.originalName;
