import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { messages } from '../../../core/messages/index.js';
import { App } from '@octokit/app';
import express from 'express';
import { createDashboardRouter } from '../dashboard/index.js';
import { createIsolationMiddleware } from '../middleware/isolamento.js';
import { createSecurityMiddleware } from '../middleware/seguranca.js';
import { createWebhookHandler } from './webhook-handler.js';
const log = messages.log;
const { GithubAppMensagens } = messages;
const HTTP_OK = 200;
const FRONTEND_DIR = join(process.cwd(), 'out');
const OCTOKIT_TIMEOUT = parseInt(process.env.TUTANUS_OCTOKIT_TIMEOUT_MS ?? '30000', 10);
export function iniciarServidorApp(opts) {
    const app = express();
    app.set('x-powered-by', false);
    app.use(express.json({
        limit: '16kb',
        verify: (req, _res, buf) => {
            req.rawBody = buf;
        }
    }));
    app.use(express.urlencoded({ extended: false, limit: '8kb' }));
    app.use(createSecurityMiddleware());
    app.use('/api/github', createIsolationMiddleware());
    const appOctokit = new App({
        appId: opts.appId,
        privateKey: opts.privateKey,
        webhooks: { secret: opts.webhookSecret },
        request: { timeout: OCTOKIT_TIMEOUT }
    });
    const webhookHandler = createWebhookHandler(appOctokit);
    app.post('/api/github/webhooks', webhookHandler);
    app.use('/api/github', createDashboardRouter(appOctokit));
    app.get('/ping', (_req, res) => {
        res.status(HTTP_OK).send('pong');
    });
    if (existsSync(FRONTEND_DIR)) {
        app.use(express.static(FRONTEND_DIR, {
            dotfiles: 'deny',
            index: false,
            setHeaders: (res) => {
                res.setHeader('X-Content-Type-Options', 'nosniff');
                res.setHeader('X-Frame-Options', 'DENY');
            }
        }));
        app.get('/{*path}', (_req, res) => {
            const indexPath = join(FRONTEND_DIR, 'index.html');
            if (existsSync(indexPath)) {
                res.sendFile(indexPath, {
                    headers: {
                        'X-Content-Type-Options': 'nosniff',
                        'X-Frame-Options': 'DENY'
                    }
                });
            }
            else {
                res.status(200).type('html').send('Tutanus API rodando.');
            }
        });
    }
    else {
        app.get('/', (_req, res) => {
            res.type('html').send('Tutanus API rodando. Landing nao encontrada (rode npm run build para gerar out/).');
        });
    }
    return new Promise((resolve, reject) => {
        try {
            app.listen(opts.port, () => {
                log.sucesso(GithubAppMensagens.servidorRodando(opts.port));
                log.info(GithubAppMensagens.webhooksEndpoint(opts.port));
                log.info(GithubAppMensagens.healthEndpoint(opts.port));
                log.info(GithubAppMensagens.dashboardEndpoint(opts.port));
                log.info(GithubAppMensagens.statsEndpoint(opts.port));
                resolve();
            });
        }
        catch (err) {
            log.erro(GithubAppMensagens.erroIniciarServidor(err instanceof Error ? err.message : String(err)));
            reject(err);
        }
    });
}
//# sourceMappingURL=server.js.map