"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateServiceToken = generateServiceToken;
exports.validateServiceToken = validateServiceToken;
exports.revokeServiceToken = revokeServiceToken;
exports.listServiceTokens = listServiceTokens;
const crypto = __importStar(require("crypto"));
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const db_1 = require("../../lib/db");
const sql_1 = require("./sql");
const TOKEN_PREFIX = 'lt_svc_';
/**
 * Generate a new service token for an external MCP server.
 * Returns the raw token once — it is never stored in plaintext.
 */
async function generateServiceToken(name, serverId, scopes, expiresAt) {
    const rawToken = `${TOKEN_PREFIX}${crypto.randomBytes(32).toString('hex')}`;
    const tokenHash = await bcryptjs_1.default.hash(rawToken, 10);
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.INSERT_SERVICE_TOKEN, [
        name, tokenHash, serverId, scopes, expiresAt || null,
    ]);
    return { id: rows[0].id, rawToken };
}
/**
 * Validate a raw service token. Returns the record if valid, null otherwise.
 */
async function validateServiceToken(rawToken) {
    if (!rawToken.startsWith(TOKEN_PREFIX))
        return null;
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_ALL_ACTIVE_SERVICE_TOKENS);
    for (const row of rows) {
        if (await bcryptjs_1.default.compare(rawToken, row.token_hash)) {
            await pool.query(sql_1.UPDATE_SERVICE_TOKEN_LAST_USED, [row.id]);
            const { token_hash, ...record } = row;
            return record;
        }
    }
    return null;
}
/**
 * Revoke (delete) a service token by ID.
 */
async function revokeServiceToken(id) {
    const pool = await (0, db_1.getPool)();
    const result = await pool.query(sql_1.DELETE_SERVICE_TOKEN, [id]);
    return (result.rowCount ?? 0) > 0;
}
/**
 * List service tokens for an MCP server (without hashes).
 */
async function listServiceTokens(serverId) {
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.LIST_SERVICE_TOKENS_BY_SERVER, [serverId]);
    return rows;
}
