const fs = require('fs');
const path = require('path');

// File categories
const categories = {
    videos: ['mp4', 'mkv', 'avi', 'mov'],
    images: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'],
    music: ['mp3', 'wav', 'flac', 'aac', 'ogg'],
    documents: ['pdf', 'doc', 'docx', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'],
    apps: ['exe', 'dmg', 'apk', 'appimage', 'deb'],
    others: [] // Catch-all for uncategorized files
};

// Organize files function
const organizeFiles = (directory) => {
    try {
        // Check if the directory exists
        if (!fs.existsSync(directory)) {
            throw new Error(`Directory does not exist: ${directory}`);
        }

        // Ensure each category folder exists
        Object.keys(categories).forEach(category => {
            const categoryPath = path.join(directory, category);
            if (!fs.existsSync(categoryPath)) {
                fs.mkdirSync(categoryPath);
            }
        });

        // Read and classify files
        const files = fs.readdirSync(directory);

        files.forEach(file => {
            const filePath = path.join(directory, file);

            // Skip directories
            if (fs.lstatSync(filePath).isFile()) {
                const ext = path.extname(file).toLowerCase().substring(1); // Get file extension without the dot
                let moved = false;

                // Check file type and move to the appropriate folder
                for (const [category, extensions] of Object.entries(categories)) {
                    if (extensions.includes(ext)) {
                        const targetPath = path.join(directory, category, file);

                        // Move the file
                        fs.renameSync(filePath, targetPath);
                        console.log(`Moved ${file} to ${category} folder`);
                        moved = true;
                        break; // Exit the loop once the file is moved
                    }
                }

                // Move uncategorized files to 'others'
                if (!moved) {
                    const othersPath = path.join(directory, 'others', file);
                    fs.renameSync(filePath, othersPath);
                    console.log(`Moved ${file} to others folder`);
                }
            }
        });

        console.log('File organization completed successfully.');
    } catch (error) {
        console.error('Error organizing files:', error.message);
        throw error; // Re-throw the error to handle it in the calling function
    }
};

module.exports = organizeFiles;