import multer from 'multer';
import path from 'path';
import fs from 'fs';



// ================= UPLOAD DIRECTORY =================

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

if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// ================= STORAGE =================

const storage = multer.diskStorage({

    destination: (req, file, cb) => {

        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {

        const filePath = path.join(
            uploadDir,
            file.originalname
        );

        // duplicate image check

        if (fs.existsSync(filePath)) {

            return cb(
                new Error('Same receipt already uploaded'),
                false
            );
        }
        // original name save

        cb(null, file.originalname);
    }
});
// ================= FILE FILTER =================

const fileFilter = (req, file, cb) => {

    const allowedTypes = /jpeg|jpg|png|gif|webp/;

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

    const mimetype = allowedTypes.test(file.mimetype);

    if (mimetype && extname) {

        cb(null, true);

    } else {

        cb(
            new Error(
                'Only image files are allowed (jpeg, jpg, png, gif, webp)'
            )
        );
    }
};

// ================= MULTER =================

const upload = multer({

    storage,

    limits: {
        fileSize: 5 * 1024 * 1024
    },

    fileFilter
});

//================= EXPORT =================

export const receiptUpload =
    upload.single('receipt');

// ================= ERROR HANDLER =================

export const uploadErrorHandler = (
    err,
    req,
    res,
    next
) => {

    if (err) {

        return res.status(400).json({
            success: false,
            message: err.message
        });
    }

    next();
};