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", "sales-regular-receipts");

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 validateRegularSaleReceiptFile(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 resi maksimal 5MB.";
  }
  return null;
}

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