import { ALLOWED_IMAGE_TYPES } from "@/lib/media/constants";

import type { MediaItem } from "./types";

export class UploadError extends Error {}

/** Quick client-side check, so obviously wrong files fail before uploading. The server re-validates. */
export function preflightImage(file: File, maxMb: number) {
  const type = file.type === "image/jpg" ? "image/jpeg" : file.type;
  if (type && !(type in ALLOWED_IMAGE_TYPES)) {
    return `${file.name}: only JPG, PNG, WebP and AVIF images are supported.`;
  }
  if (file.size > maxMb * 1024 * 1024) {
    return `${file.name} is larger than ${maxMb} MB.`;
  }
  return null;
}

/**
 * Uploads one image to the media library. Uses XMLHttpRequest because fetch
 * can't report upload progress.
 */
export function uploadImage(
  file: File,
  {
    onProgress,
    signal,
    alt,
  }: {
    onProgress?: (percent: number) => void;
    signal?: AbortSignal;
    alt?: string;
  } = {},
) {
  return new Promise<MediaItem>((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const body = new FormData();
    body.append("file", file);
    if (alt) body.append("alt", alt);

    xhr.open("POST", "/api/admin/media");
    xhr.responseType = "json";

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        onProgress?.(Math.round((event.loaded / event.total) * 100));
      }
    };
    xhr.onload = () => {
      const response = xhr.response as {
        media?: MediaItem;
        error?: string;
      } | null;
      if (xhr.status >= 200 && xhr.status < 300 && response?.media) {
        onProgress?.(100);
        resolve(response.media);
      } else {
        reject(
          new UploadError(
            response?.error ??
              (xhr.status === 413
                ? "The image is too large."
                : `Upload failed (${xhr.status || "network error"}).`),
          ),
        );
      }
    };
    xhr.onerror = () =>
      reject(
        new UploadError("Network error. Check your connection and retry."),
      );
    xhr.onabort = () => reject(new UploadError("Upload cancelled."));

    signal?.addEventListener("abort", () => xhr.abort(), { once: true });
    xhr.send(body);
  });
}

/** Images from a drop or paste event, ignoring anything else. */
export function imageFilesFrom(
  list: FileList | DataTransferItemList | null | undefined,
) {
  if (!list) return [];
  const files: File[] = [];
  for (const item of Array.from(list as ArrayLike<File | DataTransferItem>)) {
    const file =
      item instanceof File
        ? item
        : item.kind === "file"
          ? item.getAsFile()
          : null;
    if (file && file.type.startsWith("image/")) files.push(file);
  }
  return files;
}
