"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const http = __importStar(require("http"));
const PORT = 3098;
process.env.PORT = String(PORT);
process.env.TELEGRAM_BOT_TOKEN = '';
process.env.OPENLIFE_TRIGGER_TEST_ECHO = '1';
async function post(pathStr, body, headers = {}) {
    return new Promise((resolve, reject) => {
        const payload = JSON.stringify(body);
        const req = http.request({
            host: '127.0.0.1',
            port: PORT,
            path: pathStr,
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), ...headers },
            timeout: 5000
        }, (res) => {
            let chunks = '';
            res.on('data', (d) => { chunks += d; });
            res.on('end', () => resolve({ status: res.statusCode || 0, body: chunks }));
        });
        req.on('error', reject);
        req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
        req.write(payload);
        req.end();
    });
}
function basicAuthHeader(user, pass) {
    return 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64');
}
async function bootGateway() {
    const { Gateway } = require('./orchestrator/Gateway');
    const gateway = new Gateway();
    gateway.start();
    await new Promise((r) => setTimeout(r, 500));
    return gateway;
}
async function caseAuthEnabled() {
    process.env.OPENLIFE_TRIGGER_USER = 'webhook-user';
    process.env.OPENLIFE_TRIGGER_PASS = 'webhook-pass';
    const gateway = await bootGateway();
    try {
        const noAuth = await post('/api/v1/trigger', { text: 'ping' });
        if (noAuth.status !== 401)
            throw new Error(`AUTH_ENABLED_BUT_NO_AUTH_REQUEST_GOT_${noAuth.status}: ${noAuth.body}`);
        const wrongPass = await post('/api/v1/trigger', { text: 'ping' }, { Authorization: basicAuthHeader('webhook-user', 'wrong') });
        if (wrongPass.status !== 403)
            throw new Error(`WRONG_CREDS_GOT_${wrongPass.status}: ${wrongPass.body}`);
        const goodAuth = await post('/api/v1/trigger', { text: 'ping smoke' }, { Authorization: basicAuthHeader('webhook-user', 'webhook-pass') });
        if (goodAuth.status !== 200 && goodAuth.status !== 500) {
            throw new Error(`VALID_CREDS_GOT_${goodAuth.status} (expected 200 or 500-when-no-LLM): ${goodAuth.body}`);
        }
    }
    finally {
        await gateway.shutdown('TEST_AUTH_ENABLED');
    }
}
async function caseAuthDisabled() {
    delete process.env.OPENLIFE_TRIGGER_USER;
    delete process.env.OPENLIFE_TRIGGER_PASS;
    const gateway = await bootGateway();
    try {
        const r = await post('/api/v1/trigger', { text: 'ping unauth' });
        if (r.status === 401 || r.status === 403)
            throw new Error(`UNAUTHED_MODE_REJECTED_${r.status}: ${r.body}`);
    }
    finally {
        await gateway.shutdown('TEST_AUTH_DISABLED');
    }
}
async function main() {
    await caseAuthEnabled();
    await caseAuthDisabled();
    console.log('TEST_TRIGGER_BASIC_AUTH_OK');
}
main().catch((err) => {
    console.error('TEST_TRIGGER_BASIC_AUTH_FAIL:', err?.message || err);
    process.exit(1);
});
