"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 });
/*
 * INT-03 + INT-04 — Live integration test against HTTP gateway.
 *
 * Boots a real Gateway on port 4099, hits /api/v1/trigger and admin endpoints
 * with Basic Auth, asserts shape. Shuts down gracefully.
 *
 * NOT included in test:all. Run via: npm run test:integration-http
 */
const dotenv = __importStar(require("dotenv"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const http = __importStar(require("http"));
const Gateway_1 = require("./orchestrator/Gateway");
dotenv.config();
const PORT = 4099;
const TRIGGER_LOG = path.join(process.cwd(), 'docs', 'audit', 'integrations', 'http-trigger.log');
const ADMIN_LOG = path.join(process.cwd(), 'docs', 'audit', 'integrations', 'admin.log');
function log(file, line) {
    fs.mkdirSync(path.dirname(file), { recursive: true });
    fs.appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
}
function request(method, path, headers, body) {
    return new Promise((resolve, reject) => {
        const req = http.request({
            host: '127.0.0.1', port: PORT, method, path,
            headers: { ...headers, ...(body ? { 'Content-Length': Buffer.byteLength(body).toString() } : {}) }
        }, (res) => {
            let buf = '';
            res.on('data', (d) => { buf += d.toString(); });
            res.on('end', () => resolve({ status: res.statusCode || 0, headers: res.headers, body: buf }));
        });
        req.on('error', reject);
        req.setTimeout(10000, () => req.destroy(new Error('REQUEST_TIMEOUT')));
        if (body)
            req.write(body);
        req.end();
    });
}
async function main() {
    // Force credentials for this test (do not leak real ones to test code)
    process.env.PORT = String(PORT);
    process.env.OPENLIFE_TRIGGER_USER = 'audit-trigger';
    process.env.OPENLIFE_TRIGGER_PASS = 'audit-pass-' + process.pid;
    process.env.OPENLIFE_ADMIN_USER = 'audit-admin';
    process.env.OPENLIFE_ADMIN_PASS = 'audit-adminpass-' + process.pid;
    const triggerAuth = 'Basic ' + Buffer.from(`audit-trigger:${process.env.OPENLIFE_TRIGGER_PASS}`).toString('base64');
    const adminAuth = 'Basic ' + Buffer.from(`audit-admin:${process.env.OPENLIFE_ADMIN_PASS}`).toString('base64');
    const gateway = new Gateway_1.Gateway();
    gateway.start();
    // Give Express + Telegraf launch a beat
    await new Promise((r) => setTimeout(r, 2000));
    const failures = [];
    try {
        // INT-03: /api/v1/trigger
        log(TRIGGER_LOG, '----- INT-03 /api/v1/trigger -----');
        // 3a: no auth → 401
        const r1 = await request('POST', '/api/v1/trigger', { 'Content-Type': 'application/json' }, JSON.stringify({ text: 'audit ping' }));
        log(TRIGGER_LOG, `no-auth status=${r1.status} body=${r1.body.slice(0, 100)}`);
        if (r1.status !== 401)
            failures.push(`trigger no-auth expected 401 got ${r1.status}`);
        // 3b: wrong pass → 403
        const wrongAuth = 'Basic ' + Buffer.from('audit-trigger:wrong').toString('base64');
        const r2 = await request('POST', '/api/v1/trigger', { 'Content-Type': 'application/json', 'Authorization': wrongAuth }, JSON.stringify({ text: 'audit ping' }));
        log(TRIGGER_LOG, `wrong-pass status=${r2.status} body=${r2.body.slice(0, 100)}`);
        if (r2.status !== 403)
            failures.push(`trigger wrong-pass expected 403 got ${r2.status}`);
        // 3c: valid auth → 200
        const r3 = await request('POST', '/api/v1/trigger', { 'Content-Type': 'application/json', 'Authorization': triggerAuth }, JSON.stringify({ text: 'audit ping via INT-03' }));
        log(TRIGGER_LOG, `valid-auth status=${r3.status} body=${r3.body.slice(0, 200)}`);
        if (r3.status !== 200 && r3.status !== 202 && r3.status !== 500) {
            failures.push(`trigger valid-auth expected 200/202/500 got ${r3.status}`);
        }
        // 500 is acceptable: Brain may fail downstream when running without full env
        // INT-04: admin endpoints
        log(ADMIN_LOG, '----- INT-04 admin endpoints -----');
        const adminEndpoints = ['/api/v1/admin/teams', '/api/v1/admin/networks', '/api/v1/admin/status'];
        for (const ep of adminEndpoints) {
            // no auth → 401
            const ra = await request('GET', ep, {});
            log(ADMIN_LOG, `${ep} no-auth status=${ra.status}`);
            if (ra.status !== 401)
                failures.push(`${ep} no-auth expected 401 got ${ra.status}`);
            // valid auth → 200
            const rb = await request('GET', ep, { 'Authorization': adminAuth });
            let parsed;
            try {
                parsed = JSON.parse(rb.body);
            }
            catch {
                parsed = null;
            }
            const ok = rb.status === 200 && parsed && typeof parsed === 'object';
            log(ADMIN_LOG, `${ep} valid-auth status=${rb.status} json_ok=${!!parsed} preview=${rb.body.slice(0, 120)}`);
            if (!ok)
                failures.push(`${ep} valid-auth expected 200+JSON got status=${rb.status} parsed=${!!parsed}`);
        }
    }
    finally {
        try {
            await gateway.shutdown('TEST_DONE');
        }
        catch (e) {
            log(TRIGGER_LOG, `shutdown_error: ${e?.message || e}`);
        }
        delete process.env.OPENLIFE_TRIGGER_PASS;
        delete process.env.OPENLIFE_ADMIN_PASS;
    }
    if (failures.length > 0) {
        throw new Error(`HTTP_INTEGRATION_FAILURES (${failures.length}):\n${failures.join('\n')}`);
    }
    console.log(`TEST_INTEGRATION_HTTP_TRIGGER_LIVE_OK (trigger=3 cases, admin=${adminEndpoints_count()} endpoints × 2 auth states)`);
    console.log(`  trigger log: ${TRIGGER_LOG}`);
    console.log(`  admin log:   ${ADMIN_LOG}`);
}
function adminEndpoints_count() { return 3; }
main().catch((err) => {
    console.error('TEST_INTEGRATION_HTTP_TRIGGER_LIVE_FAIL:', err?.message || err);
    process.exit(1);
});
