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

const uploadRoot = path.join(process.cwd(), 'public', 'uploads');

const ensureDirectory = (dirPath: string) => {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
    }
};

// Configure disk storage
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        let folder = 'misc';
        if (file.fieldname === 'profileImage') folder = 'profiles';
        else if (file.fieldname === 'signature') folder = 'signatures';
        else if (file.fieldname === 'image') folder = 'patients';
        else if (file.fieldname === 'file') folder = 'clinical';

        const dir = path.join(uploadRoot, folder);
        ensureDirectory(dir);
        cb(null, dir);
    },
    filename: (_req, file, cb) => {
        const ext = path.extname(file.originalname) || '';
        const safeExt = ext.toLowerCase();
        const unique = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
        cb(null, `${unique}${safeExt}`);
    }
});

// File filter (images only)
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp|pdf/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);

    if (extname && mimetype) {
        return cb(null, true);
    } else {
        cb(new Error('Only image files are allowed!'));
    }
};

export const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB limit
    }
});
