import { GithubWebhookMensagens } from '../../../core/messages/index.js';
import { statsStore } from '../dashboard/stats-store.js';
import { analisarWorkflows, buscarWorkflows } from './workflow-reader.js';
const TRIGGER_TOKEN = '@tutanus scan';
const MAX_DETALHES = 10;
export async function processarIssues(app, payload) {
    const { repository, issue, installation, action } = payload;
    if (action !== 'opened')
        return;
    if (!installation?.id)
        return;
    const issueBody = (issue.body || '').toLowerCase();
    if (!issueBody.includes(TRIGGER_TOKEN))
        return;
    const owner = repository.owner.login;
    const repo = repository.name;
    const issueNumber = issue.number;
    const octokit = await app.getInstallationOctokit(installation.id);
    try {
        const { data: repoInfo } = await octokit.request('GET /repos/{owner}/{repo}', { owner, repo });
        const defaultBranch = repoInfo.default_branch;
        const workflows = await buscarWorkflows(octokit, owner, repo, defaultBranch);
        if (workflows.length === 0) {
            await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
                owner,
                repo,
                issue_number: issueNumber,
                body: GithubWebhookMensagens.nenhumWorkflowRepo
            });
            return;
        }
        const { ocorrencias, scoreGeral, workflowsInfo } = await analisarWorkflows(octokit, owner, repo, defaultBranch, workflows);
        statsStore.recordAnalysis({
            repository: `${owner}/${repo}`,
            event: 'issues',
            score: scoreGeral,
            workflowsCount: workflows.length,
            occurrencesCount: ocorrencias.length
        });
        const comment = renderIssuesComment(scoreGeral, workflowsInfo, ocorrencias);
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner,
            repo,
            issue_number: issueNumber,
            body: comment
        });
    }
    catch (err) {
        const error = err;
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
            owner,
            repo,
            issue_number: issueNumber,
            body: GithubWebhookMensagens.erroScan(error.message)
        });
    }
}
function renderIssuesComment(scoreGeral, workflowsInfo, ocorrencias) {
    let comment = `## Tutanus - Scan Sob Demanda\n\n**Score Geral:** ${scoreGeral}/100\n\n`;
    for (const wf of workflowsInfo) {
        const icon = wf.score >= 80 ? '[OK]' : wf.score >= 50 ? '[AVISO]' : '[ERRO]';
        comment += `- ${icon} **${wf.nome}** (Score: ${wf.score}/100, ${wf.ocorrencias} ocorrências)\n`;
    }
    if (ocorrencias.length > 0) {
        const erros = ocorrencias.filter(o => o.nivel === 'erro');
        const avisos = ocorrencias.filter(o => o.nivel === 'aviso');
        if (erros.length > 0) {
            comment += `\n#### Erros (${erros.length})\n\n`;
            for (const o of erros.slice(0, MAX_DETALHES)) {
                comment += `- \`${o.relPath}:${o.linha || 1}\` - ${o.mensagem}\n`;
            }
        }
        if (avisos.length > 0) {
            comment += `\n#### Avisos (${avisos.length})\n\n`;
            for (const o of avisos.slice(0, MAX_DETALHES)) {
                comment += `- \`${o.relPath}:${o.linha || 1}\` - ${o.mensagem}\n`;
            }
        }
    }
    else {
        comment += `\nNenhum problema encontrado. Workflows em bom estado!\n`;
    }
    return comment;
}
//# sourceMappingURL=issues-handler.js.map