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", "blogs")
    : path.join(baseDir, "project", "public", "images", "blogs");
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname); // Accept frontend UUID filename
  },
});

// File filter for images only
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("Only image files are allowed"));
  }
};

// Multer instance
const upload = multer({ storage, fileFilter });

// Export the actual working middleware
export const uploadBlogMiddleware = upload.single("featured_image");
