import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";

/** Uploaded files live outside `public/` so they are served the same way in dev and after a build. */
export const UPLOAD_ROOT = path.join(process.cwd(), "uploads");

const IMAGE_TYPES: Record<string, string> = {
  "image/jpeg": "jpg",
  "image/png": "png",
  "image/webp": "webp",
  "image/gif": "gif",
  "image/svg+xml": "svg",
};
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;

/** Saves an uploaded image and returns its public URL, or null when no file was chosen. */
export async function saveImage(file: FormDataEntryValue | null, folder: "products") {
  if (!(file instanceof File) || file.size === 0) return null;
  const extension = IMAGE_TYPES[file.type];
  if (!extension) throw new Error("UNSUPPORTED_IMAGE");
  if (file.size > MAX_IMAGE_BYTES) throw new Error("IMAGE_TOO_LARGE");
  const name = `${randomUUID()}.${extension}`;
  await mkdir(path.join(UPLOAD_ROOT, folder), { recursive: true });
  await writeFile(path.join(UPLOAD_ROOT, folder, name), Buffer.from(await file.arrayBuffer()));
  return `/api/uploads/${folder}/${name}`;
}

export function contentTypeFor(fileName: string) {
  const extension = fileName.split(".").pop()?.toLowerCase() ?? "";
  return Object.entries(IMAGE_TYPES).find(([, ext]) => ext === extension)?.[0] ?? "application/octet-stream";
}
