import { messages } from '../../../core/messages/index.js';
import { Router } from 'express';
import { listarConfigsInstalacao, obterConfigInstalacao, salvarConfigInstalacao } from '../app/installation-store.js';
import { buildSetupUrl, createSetupRouter } from '../app/setup-routes.js';
import { analisarWorkflows, buscarWorkflows } from '../app/webhook-handler.js';
import { criarJob, iniciarAnaliseCompleta, iniciarAutoFix, listarJobs, obterJob } from '../jobs/index.js';
import { exigeAutenticacao } from '../middleware/autenticacao.js';
import { statsStore } from './stats-store.js';
const { GithubDashboardMensagens } = messages;
const HTTP_BAD_REQUEST = 400;
const HTTP_NOT_FOUND = 404;
const DEFAULT_SCORE = 100;
function validarParams(body, campos) {
    for (const campo of campos) {
        const val = body[campo];
        if (val === undefined || val === null || val === '') {
            return `${campo} é obrigatório`;
        }
    }
    return null;
}
export function createDashboardRouter(app) {
    const router = Router();
    router.use(createSetupRouter(app));
    router.get('/app-info', (req, res) => {
        const slug = process.env.GITHUB_APP_SLUG || 'tutanus-analyzer';
        res.json({
            slug,
            installUrl: `https://github.com/apps/${slug}/installations/new`,
            appUrl: `https://github.com/apps/${slug}`,
            setupUrl: buildSetupUrl(req),
        });
    });
    router.get('/health', (_req, res) => {
        res.json(statsStore.getHealth());
    });
    router.use(exigeAutenticacao);
    router.get('/instalacoes/config', (_req, res) => {
        res.json({ instalacoes: listarConfigsInstalacao() });
    });
    router.get('/instalacoes/:id/config', (req, res) => {
        const id = parseInt(req.params.id, 10);
        if (Number.isNaN(id)) {
            res.status(HTTP_BAD_REQUEST).json({ erro: GithubDashboardMensagens.installationIdInvalido });
            return;
        }
        res.json(obterConfigInstalacao(id));
    });
    router.patch('/instalacoes/:id/config', (req, res) => {
        const id = parseInt(req.params.id, 10);
        if (Number.isNaN(id)) {
            res.status(HTTP_BAD_REQUEST).json({ erro: GithubDashboardMensagens.installationIdInvalido });
            return;
        }
        const body = req.body;
        res.json(salvarConfigInstalacao({ installationId: id, ...body }));
    });
    router.get('/stats', (_req, res) => {
        res.json(statsStore.getStats());
    });
    router.delete('/stats', (_req, res) => {
        statsStore.reset();
        res.json({ sucesso: true, mensagem: GithubDashboardMensagens.statsZeradas });
    });
    router.get('/acoes/instalacoes', async (_req, res) => {
        try {
            const { data: installations } = await app.octokit.request('GET /app/installations', {
                per_page: 100
            });
            res.json(installations.map(inst => ({
                id: inst.id,
                account: inst.account ? { login: inst.account.login, avatar_url: inst.account.avatar_url } : null,
                target_type: inst.target_type,
                repository_selection: inst.repository_selection,
                created_at: inst.created_at,
                updated_at: inst.updated_at
            })));
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    router.get('/acoes/instalacoes/:id/repos', async (req, res) => {
        try {
            const installationId = parseInt(req.params.id, 10);
            if (Number.isNaN(installationId)) {
                res.status(HTTP_BAD_REQUEST).json({ erro: 'ID de instalação inválido' });
                return;
            }
            const octokit = await app.getInstallationOctokit(installationId);
            const { data } = await octokit.request('GET /installation/repositories', {
                per_page: 100
            });
            res.json(data.repositories.map(repo => ({
                id: repo.id,
                name: repo.name,
                full_name: repo.full_name,
                owner: repo.owner?.login,
                private: repo.private,
                default_branch: repo.default_branch,
                updated_at: repo.updated_at
            })));
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    router.post('/acoes/analisar', async (req, res) => {
        try {
            const body = req.body;
            const owner = body.owner;
            const repo = body.repo;
            const installationId = body.installationId;
            const ref = body.ref;
            const erro = validarParams(body, ['owner', 'repo', 'installationId']);
            if (erro) {
                res.status(HTTP_BAD_REQUEST).json({ erro });
                return;
            }
            const octokit = await app.getInstallationOctokit(installationId);
            const branchRef = ref || 'HEAD';
            const workflows = await buscarWorkflows(octokit, owner, repo, branchRef);
            if (workflows.length === 0) {
                res.json({
                    sucesso: true,
                    scoreGeral: DEFAULT_SCORE,
                    workflows: [],
                    ocorrencias: [],
                    mensagem: GithubDashboardMensagens.nenhumWorkflowEncontrado
                });
                return;
            }
            const analysis = await analisarWorkflows(octokit, owner, repo, branchRef, workflows);
            const repoName = `${owner}/${repo}`;
            statsStore.recordAnalysis({
                repository: repoName,
                event: 'on_demand',
                score: analysis.scoreGeral,
                workflowsCount: analysis.workflowsInfo.length,
                occurrencesCount: analysis.ocorrencias.length
            });
            res.json({
                sucesso: true,
                scoreGeral: analysis.scoreGeral,
                workflows: analysis.workflowsInfo,
                ocorrencias: analysis.ocorrencias.slice(0, 50),
                totalOcorrencias: analysis.ocorrencias.length
            });
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    router.get('/acoes/resultados', (_req, res) => {
        const stats = statsStore.getStats();
        res.json({
            totalAnalyses: stats.totalAnalyses,
            recentAnalyses: stats.recentAnalyses
        });
    });
    router.post('/acoes/analisar-completo', (req, res) => {
        try {
            const body = req.body;
            const owner = body.owner;
            const repo = body.repo;
            const installationId = body.installationId;
            const ref = body.ref;
            const fast = body.fast;
            const analistas = body.analistas;
            const autoFix = body.autoFix;
            const autoFixMode = body.autoFixMode;
            const erro = validarParams(body, ['owner', 'repo', 'installationId']);
            if (erro) {
                res.status(HTTP_BAD_REQUEST).json({ erro });
                return;
            }
            const branchRef = ref || 'HEAD';
            const jobOptions = { fast: fast ?? false, analistas, autoFix: autoFix ?? false, autoFixMode };
            const jobId = criarJob(owner, repo, installationId, branchRef, jobOptions);
            const job = obterJob(jobId);
            if (!job) {
                res.status(500).json({ erro: messages.GithubDashboardMensagens.erroCriarJob });
                return;
            }
            if (autoFix) {
                void iniciarAutoFix(app, jobId, job);
            }
            else {
                void iniciarAnaliseCompleta(app, jobId, job);
            }
            res.status(202).json({
                sucesso: true,
                dados: {
                    jobId,
                    status: 'pendente',
                    mensagem: GithubDashboardMensagens.jobEnfileirado(jobId)
                }
            });
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    router.get('/acoes/analisar-completo', (_req, res) => {
        try {
            const { owner, repo } = _req.query;
            const filtro = owner && repo ? { owner, repo } : undefined;
            const jobs = listarJobs(filtro);
            res.json({ sucesso: true, dados: { total: jobs.length, jobs } });
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    router.get('/acoes/analisar-completo/:jobId', (req, res) => {
        try {
            const job = obterJob(req.params.jobId);
            if (!job) {
                res.status(HTTP_NOT_FOUND).json({ erro: GithubDashboardMensagens.jobNaoEncontrado(String(req.params.jobId)) });
                return;
            }
            res.json({ sucesso: true, dados: job });
        }
        catch (err) {
            const error = err;
            res.status(500).json({ erro: error.message });
        }
    });
    return router;
}
//# sourceMappingURL=routes.js.map