const fs = require('fs');

module.exports = function (app, checkApiKey) {
    app.post('/action/delperm', checkApiKey, (req, res) => {
        const authzFilePath = '/etc/apache2/dav_svn.authz';

        const { repoName, user } = req.body;

        console.log("Nom du repo reçu :", repoName); // DEBUG
        console.log("Utilisateur reçu :", user); // DEBUG

        if (!repoName || !user) {
            return res.status(400).json({ error: "Missing repoName or user parameter" });
        }

        try {
            const fileContent = fs.readFileSync(authzFilePath, 'utf8');

            console.log("Contenu du fichier avant modification :");
            console.log(fileContent); // DEBUG

            const repoRegex = new RegExp(`(\\[/${repoName}\\][^\\[]*)(?=\\[|$)`, 'gs');
            const match = repoRegex.exec(fileContent);

            if (!match) {
                return res.status(400).json({ error: "Repository section not found" });
            }

            const fullRepoSection = match[0];
            const lines = fullRepoSection.split('\n');

            const newLines = lines.filter(line => {
                const trimmed = line.trim();
                return !trimmed.startsWith(user + ' =');
            });

            const updatedRepoSection = newLines.join('\n');

            const newFileContent = fileContent.replace(fullRepoSection, updatedRepoSection);

            console.log("Contenu du fichier après modification :");
            console.log(newFileContent); // DEBUG

            fs.writeFileSync(authzFilePath, newFileContent, 'utf8');

            res.json({ message: 'Permission removed successfully' });

        } catch (error) {
            res.status(500).json({
                error: "Error processing repository permissions",
                details: error.message
            });
        }
    });
};
