"use strict";
// =============================================================================
// Pure Agent - Webhook Platform Adapter
// Generic HTTP webhook for receiving and sending messages
// =============================================================================
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookAdapter = void 0;
const express_1 = require("express");
const config_1 = require("../config");
const base_1 = require("./base");
const logger_1 = require("../../logger");
const platform_registry_1 = require("../platform-registry");
// ---------------------------------------------------------------------------
// WebhookAdapter
// ---------------------------------------------------------------------------
class WebhookAdapter extends base_1.BasePlatformAdapter {
    _router = null;
    _port;
    constructor(config) {
        super(config_1.Platform.WEBHOOK, config);
        this._port = parseInt(config.extra?.port || '3001', 10);
    }
    getRouter() {
        if (!this._router) {
            this._router = (0, express_1.Router)();
            this._setupRoutes();
        }
        return this._router;
    }
    _setupRoutes() {
        const router = this._router;
        // POST /webhook/message - receive a message
        router.post('/message', async (req, res) => {
            try {
                const { text, chat_id, user_id, user_name, message_id, reply_to } = req.body;
                if (!text || !chat_id) {
                    return res.status(400).json({ error: 'Missing text or chat_id' });
                }
                const event = {
                    text,
                    messageType: base_1.MessageType.TEXT,
                    platform: config_1.Platform.WEBHOOK,
                    chatId: chat_id,
                    chatType: 'dm',
                    userId: user_id,
                    userName: user_name,
                    messageId: message_id,
                    replyToMessageId: reply_to,
                    timestamp: Date.now(),
                    rawMessage: req.body,
                };
                await this.handleMessage(event);
                res.json({ ok: true });
            }
            catch (err) {
                (0, logger_1.getLogger)().error(`Webhook error: ${err.message}`);
                res.status(500).json({ error: err.message });
            }
        });
        // GET /webhook/health
        router.get('/health', (_req, res) => {
            res.json({ status: 'ok', connected: this._connected });
        });
    }
    async connect() {
        this._connected = true;
        (0, logger_1.getLogger)().info(`Webhook adapter connected (listening on port ${this._port})`);
        return true;
    }
    async disconnect() {
        this._connected = false;
        (0, logger_1.getLogger)().info('Webhook adapter disconnected');
    }
    async send(chatId, content, replyTo) {
        // Webhook is receive-only; outgoing messages need a callback URL
        (0, logger_1.getLogger)().debug(`Webhook send to ${chatId}: ${content.slice(0, 100)}`);
        return { success: true, messageId: `wh_${Date.now()}` };
    }
    async getChatInfo(chatId) {
        return { name: `webhook:${chatId}`, type: 'dm' };
    }
}
exports.WebhookAdapter = WebhookAdapter;
// Auto-register
platform_registry_1.platformRegistry.register({
    name: 'webhook',
    label: 'Webhook',
    factory: (config) => new WebhookAdapter(config),
    emoji: '🔗',
    maxMessageLength: 0, // No limit
});
//# sourceMappingURL=webhook.js.map