import { GithubSetupMensagens, messages } from '../../../core/messages/index.js';
import { Router } from 'express';
import { salvarConfigInstalacao } from './installation-store.js';
const HTTP_BAD_REQUEST = 400;
function publicBaseUrl(req) {
    const env = process.env.TUTANUS_PUBLIC_URL || process.env.PUBLIC_URL;
    if (env)
        return env.replace(/\/$/, '');
    const proto = req.headers['x-forwarded-proto'] || req.protocol;
    const host = req.headers['x-forwarded-host'] || req.headers.host;
    return `${proto}://${host}`;
}
export function createSetupRouter(app) {
    const router = Router();
    router.get('/setup', async (req, res) => {
        const installationIdRaw = req.query.installation_id;
        const setupAction = typeof req.query.setup_action === 'string' ? req.query.setup_action : 'install';
        const installationId = typeof installationIdRaw === 'string'
            ? parseInt(installationIdRaw, 10)
            : Array.isArray(installationIdRaw)
                ? parseInt(installationIdRaw[0], 10)
                : NaN;
        if (!installationId || Number.isNaN(installationId)) {
            res.status(HTTP_BAD_REQUEST).type('html').send(GithubSetupMensagens.installationIdAusente);
            return;
        }
        try {
            salvarConfigInstalacao({
                installationId,
                pushAnalysisEnabled: true,
                pullRequestAnalysisEnabled: true,
                fast: false,
                incrementalOnPush: true
            });
        }
        catch (err) {
            messages.log.erro(`${GithubSetupMensagens.erroSalvarConfig}: ${err instanceof Error ? err.message : String(err)}`);
        }
        let destino = 'https://github.com';
        try {
            const { data: installation } = await app.octokit.request('GET /app/installations/{installation_id}', {
                installation_id: installationId,
            });
            const account = installation.account;
            const username = account && 'login' in account ? account.login :
                account && 'slug' in account ? account.slug : null;
            if (username) {
                destino = `https://github.com/${username}`;
            }
        }
        catch (err) {
            messages.log.erro(`Falha ao buscar instalacao ${installationId}: ${err instanceof Error ? err.message : String(err)}`);
        }
        res.redirect(302, destino);
    });
    router.get('/setup-info', (req, res) => {
        const base = publicBaseUrl(req);
        res.json({
            setupUrl: `${base}/api/github/setup`,
            redirectAfterInstall: 'https://github.com/settings/installations/{installation_id}',
            instrucao: 'No painel do GitHub App, defina "Setup URL" como setupUrl. Após instalar, o usuário permanece no GitHub.'
        });
    });
    return router;
}
export function buildSetupUrl(req) {
    const env = process.env.TUTANUS_PUBLIC_URL || process.env.PUBLIC_URL;
    if (env)
        return `${env.replace(/\/$/, '')}/api/github/setup`;
    if (req) {
        const base = (() => {
            const proto = req.headers['x-forwarded-proto'] || req.protocol;
            const host = req.headers['x-forwarded-host'] || req.headers.host;
            return `${proto}://${host}`;
        })();
        return `${base}/api/github/setup`;
    }
    return '/api/github/setup';
}
//# sourceMappingURL=setup-routes.js.map