// tools/webhook.ts — Handlers for webhook management MCP tools.
// start_webhook, stop_webhook, webhook_status
import { startWebhookServer, stopWebhookServer, getWebhookState, setWebhookSecret, } from '../engine/webhook/index.js';
// ---------------------------------------------------------------------------
// Tool handlers
// ---------------------------------------------------------------------------
export async function handleStartWebhook(args) {
    const port = args.port ?? 2358;
    const secret = args.secret ?? '';
    if (port < 1 || port > 65535) {
        return {
            content: [{ type: 'text', text: 'Error: port must be between 1 and 65535.' }],
            isError: true,
        };
    }
    const current = getWebhookState();
    if (current.running) {
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        'Webhook server is already running.',
                        `Port: ${String(current.port)}`,
                        `Started: ${current.startedAt ?? 'unknown'}`,
                        '',
                        'Use stop_webhook first to restart on a different port.',
                    ].join('\n'),
                },
            ],
        };
    }
    if (secret) {
        setWebhookSecret(secret);
    }
    try {
        const state = await startWebhookServer(port);
        const secretMsg = secret
            ? 'HMAC-SHA256 signature validation enabled.'
            : 'Warning: no webhook secret set — all requests will be accepted.';
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        'Webhook server started.',
                        `URL: http://localhost:${String(state.port)}/`,
                        `Port: ${String(state.port)}`,
                        `Started: ${state.startedAt ?? 'unknown'}`,
                        '',
                        secretMsg,
                        '',
                        'Configure this URL in your Lemon Squeezy dashboard under:',
                        '  Settings > Webhooks > Add webhook',
                        '',
                        'Supported events:',
                        '  • subscription_cancelled',
                        '  • subscription_updated',
                        '  • license_key_created',
                    ].join('\n'),
                },
            ],
        };
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `Failed to start webhook server: ${message}`,
                        '',
                        'Common causes:',
                        `• Port ${String(port)} is already in use — try a different port`,
                        '• Insufficient permissions for ports below 1024',
                    ].join('\n'),
                },
            ],
            isError: true,
        };
    }
}
export async function handleStopWebhook(_args) {
    const current = getWebhookState();
    if (!current.running) {
        return {
            content: [{ type: 'text', text: 'Webhook server is not running.' }],
        };
    }
    // force flag reserved for future use (e.g., drop active connections)
    try {
        await stopWebhookServer();
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        'Webhook server stopped.',
                        `Events processed during session: ${String(current.eventsProcessed)}`,
                    ].join('\n'),
                },
            ],
        };
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return {
            content: [{ type: 'text', text: `Failed to stop webhook server: ${message}` }],
            isError: true,
        };
    }
}
export function handleWebhookStatus(args) {
    const state = getWebhookState();
    const includeEvents = args.includeEvents ?? true;
    const lines = [
        `Status: ${state.running ? 'RUNNING' : 'STOPPED'}`,
        `Port: ${String(state.port)}`,
        `Started: ${state.startedAt ?? 'N/A'}`,
        `Events processed: ${String(state.eventsProcessed)}`,
    ];
    if (includeEvents && state.recentEvents.length > 0) {
        lines.push('', 'Recent events:');
        for (const event of state.recentEvents) {
            const status = event.processed ? 'OK' : 'FAIL';
            lines.push(`  [${status}] ${event.receivedAt} | ${event.eventType} | ${event.summary}`);
        }
    }
    else if (includeEvents) {
        lines.push('', 'No events received yet.');
    }
    if (!state.running) {
        lines.push('', 'Use start_webhook to begin receiving Lemon Squeezy events.');
    }
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
    };
}
// ---------------------------------------------------------------------------
// Internal helper (exported for testing)
// ---------------------------------------------------------------------------
export function formatStateForDisplay(state) {
    return [
        `running=${String(state.running)}`,
        `port=${String(state.port)}`,
        `eventsProcessed=${String(state.eventsProcessed)}`,
    ].join(', ');
}
//# sourceMappingURL=webhook.js.map