const fs = require('fs');
const { execSync } = require('child_process');

module.exports = function(app, checkApiKey) {
    app.post('/action/deleterepo', checkApiKey, (req, res) => {
        const { repoName } = req.body;

        if (!repoName) {
            return res.status(400).send('Repository name is required');
        }

        const repoPath = `/var/svn/${repoName}`;
        const authzFilePath = '/etc/apache2/dav_svn.authz';

        try {
            // Check if repo exists
            if (!fs.existsSync(repoPath)) {
                return res.status(404).send(`Repository ${repoName} not found`);
            }

            // Delete repository directory
            execSync(`rm -rf ${repoPath}`);

            // Update authz file
            let authzContent = fs.readFileSync(authzFilePath, 'utf8');
            const repoSection = new RegExp(`\\[/${repoName}\\][^\\[]*`, 'g');
            authzContent = authzContent.replace(repoSection, '');
            
            // Clean up empty lines
            authzContent = authzContent.replace(/\n\s*\n/g, '\n');
            
            fs.writeFileSync(authzFilePath, authzContent);

            res.send(`Repository ${repoName} and its permissions deleted successfully`);

        } catch (error) {
            res.status(500).send(`Error deleting repository: ${error.message}`);
        }
    });
};
