const fs = require('fs');

module.exports = function (app, checkApiKey) {
    // Récupération des groupes SVN
    app.get('/action/getuseringroup', checkApiKey, (req, res) => {
        const authzFilePath = '/etc/apache2/dav_svn.authz';
        const groupName = req.query.group;

        if (!groupName) {
            return res.status(400).json({ error: "Missing group parameter" });
        }
        
        try {
            const fileContent = fs.readFileSync(authzFilePath, 'utf8');
            const groupsSection = fileContent.split('[groups]')[1];
            
            if (!groupsSection) {
                return res.json({
                    users: [],
                    count: 0
                });
            }
            
            const groupLine = groupsSection
                .split('\n')
                .find(line => line.startsWith(groupName + ' ='));
            
            if (!groupLine) {
                return res.json({
                    users: [],
                    count: 0
                });
            }
            
            const users = groupLine.split('=')[1].split(',').map(user => user.trim());
            
            res.json({
                users: users,
                count: users.length
            });
            
        } catch (error) {
            res.status(500).json({
                error: "Error reading groups file",
                details: error.message
            });
        }
    });
};
