const ALLOWED_EXT = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif", ".svg"]);

const MIME_TO_EXT: Record<string, string> = {
  "image/jpeg": ".jpg",
  "image/png": ".png",
  "image/webp": ".webp",
  "image/gif": ".gif",
  "image/svg+xml": ".svg",
};

export function sanitizeImageBaseName(name: string): string {
  const dot = name.lastIndexOf(".");
  const withoutExt = dot > 0 ? name.slice(0, dot) : name;
  const slug = withoutExt
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 80);
  return slug || "gorsel";
}

export function resolveImageExtension(file: File): string {
  const fromName = file.name.includes(".")
    ? file.name.slice(file.name.lastIndexOf(".")).toLowerCase()
    : "";
  if (ALLOWED_EXT.has(fromName)) return fromName;
  const fromMime = MIME_TO_EXT[file.type];
  if (fromMime) return fromMime;
  throw new Error("Desteklenmeyen dosya türü. JPG, PNG, WebP, GIF veya SVG kullanın.");
}

export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
