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

// Function to sanitize filenames in a given directory
const sanitizeFilenames = (directory) => {
    fs.readdir(directory, (err, files) => {
        if (err) {
            console.error('Error reading directory:', err);
            return;
        }

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

            // Sanitize the file name by replacing invalid characters
            const sanitizedFileName = file.replace(/[^\w\s.-]/g, '_'); 

            // Avoid renaming if the sanitized name is the same as the original name
            if (file !== sanitizedFileName) {
                const sanitizedPath = path.join(directory, sanitizedFileName);

                // Check if the sanitized file name already exists
                fs.exists(sanitizedPath, (exists) => {
                    if (exists) {
                        let counter = 1;
                        let newSanitizedPath;

                        // Generate a new file name if it already exists (appends -copy if the file exists)
                        do {
                            const newFileName = sanitizedFileName.replace(path.extname(file), `-copy${counter++}${path.extname(file)}`);
                            newSanitizedPath = path.join(directory, newFileName);
                        } while (fs.existsSync(newSanitizedPath));

                        // Rename the file to the new unique name
                        fs.rename(filePath, newSanitizedPath, err => {
                            if (err) {
                                console.error(`Error renaming file ${file}:`, err);
                            } else {
                                console.log(`Renamed ${file} to ${newSanitizedPath}`);
                            }
                        });
                    } else {
                        // If the sanitized file name doesn't exist, just rename the file
                        fs.rename(filePath, sanitizedPath, err => {
                            if (err) {
                                console.error(`Error renaming file ${file}:`, err);
                            } else {
                                console.log(`Renamed ${file} to ${sanitizedFileName}`);
                            }
                        });
                    }
                });
            }
        });
    });
};

module.exports = { sanitizeFilenames };