import multer from "multer";
import path from "path";
import fs from "fs";
import { Request } from "express";

const isProduction = process.env.NODE_ENV === "production";
const baseDir = path.join(__dirname, "..", "..", "..");

// Define storage location and naming
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = isProduction
      ? path.join(baseDir, "nytsolvers", "dist", "client", "images")
      : path.join(baseDir, "project", "public", "images");
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname); // Use frontend-provided filename
  },
});

// File filter for images (PNG, JPEG, ICO)
const fileFilter = (
  req: Request,
  file: Express.Multer.File,
  cb: multer.FileFilterCallback
) => {
  const allowedMimeTypes = [
    "image/png",
    "image/jpeg",
    "image/x-icon",
    "image/svg+xml",
    "image/vnd.microsoft.icon",
    "application/octet-stream", // common for .ico
  ];

  const allowedExtensions = [".png", ".jpg", ".jpeg", ".ico", ".svg"];
  const ext = path.extname(file.originalname).toLowerCase();

  if (
    allowedMimeTypes.includes(file.mimetype) ||
    allowedExtensions.includes(ext)
  ) {
    cb(null, true);
  } else {
    cb(new Error("Only PNG, JPEG, and ICO image files are allowed"));
  }
};

// Multer instance with size limits
const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB per file
});

// Middleware: allow up to 10 images per request
export const uploadMiddleware = upload.array("images", 10);
