import fs from "fs";
import path from "path";
import sharp from "sharp";
import crypto from "crypto";

export async function handleFileUploads(formData) {
  try {
    const folder = formData.get("folder") || "default";
    const uploadDir = path.join(process.cwd(), "public", "uploads", folder);

    // ✅ Ensure the upload directory exists
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    const uploadedFiles = {};

    // ✅ Fix: loop each key only once to avoid duplicates
    for (const key of new Set(formData.keys())) {
      if (key === "folder") continue;

      const files = formData.getAll(key);

      for (const file of files) {
        if (file && typeof file.arrayBuffer === "function") {
          const randomId = crypto.randomBytes(4).toString("hex");
          const randomNo = Math.floor(10000 + Math.random() * 12345);
          const fileName = `${Date.now()}_${randomId}_${randomNo}.webp`;
          const filePath = path.join(uploadDir, fileName);

          const buffer = Buffer.from(await file.arrayBuffer());

          await sharp(buffer).webp().toFile(filePath);

          if (!uploadedFiles[key]) {
            uploadedFiles[key] = [];
          }
          uploadedFiles[key].push(`/uploads/${folder}/${fileName}`);
        }
      }
    }

    return uploadedFiles;
  } catch (error) {
    console.error("❌ File Upload Error:", error);
    return { error: "File upload failed" };
  }
}
