"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 TOKEN_PREFIX = 'lt_svc_';
const INSERT_TOKEN = `
  INSERT INTO lt_service_tokens (name, token_hash, server_id, scopes, expires_at)
  VALUES ($1, $2, $3, $4, $5) RETURNING id`;
const GET_ALL_TOKENS = `
  SELECT id, name, token_hash FROM lt_service_tokens
  WHERE (expires_at IS NULL OR expires_at > NOW())`;
const UPDATE_LAST_USED = `
  UPDATE lt_service_tokens SET last_used_at = NOW() WHERE id = $1`;
const DELETE_TOKEN = `
  DELETE FROM lt_service_tokens WHERE id = $1`;
const LIST_BY_SERVER = `
  SELECT id, name, server_id, scopes, expires_at, last_used_at, created_at, updated_at
  FROM lt_service_tokens WHERE server_id = $1 ORDER BY created_at`;
/**
 * 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(INSERT_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(GET_ALL_TOKENS);
    for (const row of rows) {
        if (await bcryptjs_1.default.compare(rawToken, row.token_hash)) {
            await pool.query(UPDATE_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(DELETE_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(LIST_BY_SERVER, [serverId]);
    return rows;
}
