const multer = require("multer");
const path = require("path");
const { randomUUID } = require("crypto");
const fs = require("fs");

// Fungsi untuk tentuin folder berdasarkan file type
function getFolderByType(mimetype) {
  if (mimetype === "application/pdf") {
    return "pdf";
  } else if (mimetype.startsWith("image/")) {
    return "images";
  }
  return "file";
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const folderName = getFolderByType(file.mimetype);
    const folderPath = path.join(__dirname, "../uploads", folderName);

    fs.mkdirSync(folderPath, { recursive: true });

    cb(null, folderPath);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const timestamp = Date.now();

    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    const formattedDate = `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;

    // Prefix berdasarkan tipe file
    const prefix = file.mimetype === "application/pdf" ? "pdf" : "img";
    const uniqueId = randomUUID().slice(0, 8);

    cb(null, `${prefix}-${uniqueId}-${formattedDate}${ext}`);
  },
});

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|pdf/;
    const allowedMimeTypes = /image\/(jpeg|jpg|png)|application\/pdf/;

    const extname = allowedTypes.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimetype = allowedMimeTypes.test(file.mimetype);

    if (extname && mimetype) {
      return cb(null, true);
    } else {
      cb(new Error("File type not allowed. Only PDF and Images (JPEG, JPG, PNG) are accepted."));
    }
  },
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB max file size
  },
});

module.exports = upload;