// upload-middleware.js
const multer = require('multer');
const path = require('path');
const fs = require('fs');

function setupUploadMiddleware() {
    const { createUserTaskFolder } = require('./database');
    
    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            const taskId = req.body.taskId || req.params.taskId;
            const userLogin = req.session.user?.login;
            
            if (taskId && userLogin) {
                const userFolder = createUserTaskFolder(taskId, userLogin);
                cb(null, userFolder);
            } else {
                const tempDir = path.join(__dirname, 'data', 'uploads', 'temp');
                if (!fs.existsSync(tempDir)) {
                    fs.mkdirSync(tempDir, { recursive: true });
                }
                cb(null, tempDir);
            }
        },
        filename: (req, file, cb) => {
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            cb(null, uniqueSuffix + path.extname(file.originalname));
        }
    });

    return multer({
        storage: storage,
        limits: {
            fileSize: 300 * 1024 * 1024,
            files: 15
        }
    });
}

module.exports = { setupUploadMiddleware };