import { createServer } from 'http';
import { verifyWebhookSignature } from './client.js';
export function createWebhookServer(config, webhookSecret, onPR, onLog, onFileLog) {
    const server = createServer(async (req, res) => {
        const { pathname } = new URL(req.url ?? '/', `http://localhost`);
        if (pathname !== config.server.webhook_path) {
            res.writeHead(404).end();
            return;
        }
        if (req.method !== 'POST') {
            res.writeHead(405).end();
            return;
        }
        const chunks = [];
        for await (const chunk of req)
            chunks.push(chunk);
        const rawBody = Buffer.concat(chunks).toString('utf8');
        const signature = req.headers['x-hub-signature-256'] ?? '';
        if (!verifyWebhookSignature(rawBody, signature, webhookSecret)) {
            onLog('⚠  Rejected request with invalid webhook signature');
            onFileLog?.({ level: 'warn', event: 'webhook_sig_invalid', ip: req.socket.remoteAddress });
            res.writeHead(401).end();
            return;
        }
        const event = req.headers['x-github-event'];
        if (event !== 'pull_request') {
            res.writeHead(200).end('ok');
            return;
        }
        let body;
        try {
            body = JSON.parse(rawBody);
        }
        catch {
            onFileLog?.({ level: 'error', event: 'webhook_parse_error', ip: req.socket.remoteAddress });
            res.writeHead(400).end();
            return;
        }
        if (body.action === 'opened' || body.action === 'synchronize') {
            res.writeHead(200).end('ok');
            // async — don't block the webhook response
            setImmediate(() => onPR(body));
        }
        else {
            res.writeHead(200).end('ok');
        }
    });
    return server;
}
//# sourceMappingURL=webhook.js.map