export const IMAGE_TYPES = [
  "image/png",
  "image/jpeg",
  "image/gif",
  "image/webp",
] as const;

export const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB

export type AttachedFile = {
  id: string;
  file: File;
  preview: string; // object URL for thumbnail (images) or empty
  base64: string; // data URI for API
  mimeType: string;
  isImage: boolean;
};

export function isImageFile(file: File): boolean {
  return IMAGE_TYPES.includes(file.type as (typeof IMAGE_TYPES)[number]);
}

export function validateFile(file: File): string | null {
  if (file.size > MAX_FILE_SIZE) {
    return `파일 크기가 20MB를 초과합니다: ${(file.size / 1024 / 1024).toFixed(1)}MB`;
  }
  return null;
}

export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = () => reject(new Error("파일 읽기에 실패했습니다."));
    reader.readAsDataURL(file);
  });
}

export function fileToText(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = () => reject(new Error("파일 읽기에 실패했습니다."));
    reader.readAsText(file);
  });
}

/** Get a human-readable file size string */
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`;
}
