const multer = require('multer');
const path = require('path');
const fs = require('fs');
const organizeFiles = require('../utils/organizeFiles'); // Import the function to organize files
const express = require('express');

const router = express.Router();

// Base directory for uploaded files
const privateDir = path.join(__dirname, '../private');

// Ensure the upload directory exists
if (!fs.existsSync(privateDir)) {
    fs.mkdirSync(privateDir, { recursive: true });
    console.log('Created private directory for uploads');
}

// Helper function to generate a unique filename by appending '-copy'
const generateUniqueFilename = (directory, filename) => {
    const extname = path.extname(filename);
    const basename = path.basename(filename, extname);
    let newFilename = filename;
    let counter = 1;

    // Check if the file exists, if it does, append '-copy' or increment the counter
    while (fs.existsSync(path.join(directory, newFilename))) {
        newFilename = `${basename}-copy${counter++}${extname}`;
    }

    return newFilename;
};

// Multer storage configuration
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, privateDir);
    },
    filename: (req, file, cb) => {
        // Generate a unique filename if necessary
        const uniqueFilename = generateUniqueFilename(privateDir, file.originalname);
        cb(null, uniqueFilename); // Use the unique filename
    }
});

// Multer configuration with file size limit and allowing multiple files
const upload = multer({
    storage: storage,
    limits: { fileSize: 1024 * 1024 * 1024 * 10 } // 10GB limit
}).array('myFile', 999); // Allow multiple files

// File upload route
router.post('/', (req, res) => {
    upload(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            console.error(`Multer error: ${err.message}`);
            return res.status(400).json({ error: `Multer error: ${err.message}` });
        } else if (err) {
            console.error(`Upload error: ${err.message}`);
            return res.status(500).json({ error: `Upload error: ${err.message}` });
        }

        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ error: 'No files were uploaded.' });
        }

        try {
            // Organize files after upload
            organizeFiles(privateDir);

            // Collect uploaded file details
            const uploadedFiles = req.files.map(file => ({
                name: file.originalname,
                path: file.path,
                size: file.size,
                uploadedAt: new Date()
            }));

            // Respond with details of uploaded files
            return res.status(200).json({
                message: 'Files uploaded successfully!',
                files: uploadedFiles
            });
        } catch (error) {
            console.error(`Error organizing files: ${error.message}`);
            return res.status(500).json({ error: `Error organizing files: ${error.message}` });
        }
    });
});

module.exports = router;