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

const ALLOWED_FILE_TYPES = new Set(["image/jpeg", "image/png", "application/pdf"]);
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "purchase-cost-proofs");

type ParsedFile = { name: string; type: string; size: number; arrayBuffer: () => Promise<ArrayBuffer> };

function normalizeExtension(fileType: string, fileName: string) {
  if (fileType === "image/jpeg") return ".jpg";
  if (fileType === "image/png") return ".png";
  if (fileType === "application/pdf") return ".pdf";
  const extension = path.extname(fileName).toLowerCase();
  return extension || ".bin";
}

export function validatePurchaseCostProofFile(file: ParsedFile) {
  if (!ALLOWED_FILE_TYPES.has(file.type)) {
    return "Jenis file tidak valid. Gunakan jpg, png, atau pdf.";
  }
  if (file.size > 5 * 1024 * 1024) {
    return "Ukuran file bukti/resi maksimal 5MB.";
  }
  return null;
}

export async function storePurchaseCostProof(file: ParsedFile, index: number) {
  const extension = normalizeExtension(file.type, file.name);
  await mkdir(UPLOAD_DIR, { recursive: true });
  const fileName = `${Date.now()}-${index}-${randomUUID()}${extension}`;
  const destination = path.join(UPLOAD_DIR, fileName);
  await writeFile(destination, Buffer.from(await file.arrayBuffer()));
  return `/uploads/purchase-cost-proofs/${fileName}`;
}

