/** Shared document upload limits — keep in sync with backend MAX_DOCUMENT_SIZE_MB. */
export const MAX_DOCUMENT_SIZE_MB = Number(
  import.meta.env["VITE_MAX_DOCUMENT_SIZE_MB"] ?? 20,
);

export const MAX_DOCUMENT_BYTES = MAX_DOCUMENT_SIZE_MB * 1024 * 1024;

export const DOCUMENT_ACCEPT =
  "application/pdf,image/jpeg,image/png,image/webp,.pdf,.jpg,.jpeg,.png,.webp";

export const DOCUMENT_MIME_TYPES = [
  "application/pdf",
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
] as const;

export function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export function validateDocumentFile(file: File): string | null {
  if (!DOCUMENT_MIME_TYPES.includes(file.type as (typeof DOCUMENT_MIME_TYPES)[number])) {
    const ext = file.name.split(".").pop()?.toLowerCase();
    const okExt = ext && ["pdf", "jpg", "jpeg", "png", "webp"].includes(ext);
    if (!okExt) {
      return "This file type isn't supported. Please upload a PDF, JPG, PNG, or WEBP file.";
    }
  }
  if (file.size > MAX_DOCUMENT_BYTES) {
    return `This file is too large. Please upload a file smaller than ${MAX_DOCUMENT_SIZE_MB} MB.`;
  }
  if (file.size === 0) {
    return "Please choose a non-empty file.";
  }
  return null;
}

export function documentFileUrl(invoiceId: string, platform: string, email: string): string {
  const API_BASE = import.meta.env["VITE_API_URL"] ?? "/api";
  const params = new URLSearchParams({ platform, email });
  return `${API_BASE}/v1/documents/${encodeURIComponent(invoiceId)}/file?${params}`;
}
