import type { Request } from "express";
import multer from "multer";
import path from "path";
import crypto from "crypto";
import { STATIC_UPLOADS_DIR } from "@/core/storage-paths";

const UPLOADS_DIR = STATIC_UPLOADS_DIR;

const storage = multer.diskStorage({
    destination: (_req, _file, cb) => cb(null, UPLOADS_DIR),
    filename: (_req, file, cb) => {
        const ext = path.extname(file.originalname).toLowerCase() || ".jpg";
        const unique = crypto.randomUUID();
        cb(null, `${unique}${ext}`);
    },
});

const fileFilter = (_req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
    const allowed = ["image/jpeg", "image/png", "image/webp", "image/gif"];
    if (allowed.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error("Format non supporté. Formats acceptés : JPEG, PNG, WebP, GIF"));
    }
};

export const upload = multer({
    storage,
    fileFilter,
    limits: { fileSize: 2 * 1024 * 1024 }, // 2 Mo max
});

export { UPLOADS_DIR };

