import { GithubWebhookMensagens, messages } from '../../../core/messages/index.js';
import { statsStore } from '../dashboard/stats-store.js';
import { CHECK_RUN_NAME, completarCheckRun, DEFAULT_SCORE } from './check-run-builder.js';
import { analisarWorkflows, buscarWorkflows } from './workflow-reader.js';
export async function processarCheckSuite(app, payload) {
    const { repository, check_suite, installation } = payload;
    const owner = repository.owner.login;
    const repo = repository.name;
    const headSha = check_suite.head_sha;
    if (!installation?.id)
        return;
    const octokit = await app.getInstallationOctokit(installation.id);
    const { data: checkRun } = await octokit.request('POST /repos/{owner}/{repo}/check-runs', {
        owner,
        repo,
        name: CHECK_RUN_NAME,
        head_sha: headSha,
        status: 'in_progress'
    });
    try {
        const workflows = await buscarWorkflows(octokit, owner, repo, headSha);
        if (workflows.length === 0) {
            await completarCheckRun(octokit, owner, repo, checkRun.id, DEFAULT_SCORE, [], { status: 'success' });
            return;
        }
        const { ocorrencias, scoreGeral } = await analisarWorkflows(octokit, owner, repo, headSha, workflows);
        statsStore.recordAnalysis({
            repository: `${owner}/${repo}`,
            event: 'check_suite',
            score: scoreGeral,
            workflowsCount: workflows.length,
            occurrencesCount: ocorrencias.length
        });
        await completarCheckRun(octokit, owner, repo, checkRun.id, scoreGeral, ocorrencias);
    }
    catch (err) {
        const error = err;
        messages.log.erro(GithubWebhookMensagens.erroAnalise(error.message));
        await octokit.request('PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}', {
            owner,
            repo,
            check_run_id: checkRun.id,
            status: 'completed',
            conclusion: 'failure',
            output: {
                title: GithubWebhookMensagens.erroAnaliseTitle,
                summary: GithubWebhookMensagens.erroAnalise(error.message)
            }
        }).catch((errAnotacao) => {
            messages.log.erro(GithubWebhookMensagens.erroAnotacaoCheckRun(errAnotacao.message));
        });
    }
}
//# sourceMappingURL=check-suite-handler.js.map