const fs = require('fs');

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

        // Récupérer le nom du repo depuis la query string ou le body
        const repoName = req.query.repo || req.body.repo;

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

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

        try {
            const fileContent = fs.readFileSync(authzFilePath, 'utf8');
            const repoSection = fileContent.split(`[/${repoName}]`)[1];

            if (!repoSection) {
                return res.json({
                    users: [],
                    permissions: [],
                    count: 0
                });
            }

            const lines = repoSection.split('\n')
                .filter(line => line.includes('=') && !line.includes('['));

            const users = lines.map(line => line.split('=')[0].trim());
            const permissions = lines.map(line => line.split('=')[1].trim());

            res.json({
                users: users,
                permissions: permissions,
                count: users.length
            });

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