"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.generateBotApiKey = generateBotApiKey;
exports.validateBotApiKey = validateBotApiKey;
exports.revokeBotApiKey = revokeBotApiKey;
exports.listBotApiKeys = listBotApiKeys;
const crypto = __importStar(require("crypto"));
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const db_1 = require("../../lib/db");
const TOKEN_PREFIX = 'lt_bot_';
const INSERT_KEY = `
  INSERT INTO lt_bot_api_keys (name, user_id, key_hash, scopes, expires_at)
  VALUES ($1, $2, $3, $4, $5) RETURNING id`;
const GET_KEYS_BY_USER = `
  SELECT id, name, user_id, key_hash, scopes
  FROM lt_bot_api_keys
  WHERE user_id = $1
    AND (expires_at IS NULL OR expires_at > NOW())`;
const GET_ALL_ACTIVE_KEYS = `
  SELECT id, name, user_id, key_hash, scopes
  FROM lt_bot_api_keys
  WHERE (expires_at IS NULL OR expires_at > NOW())`;
const UPDATE_LAST_USED = `
  UPDATE lt_bot_api_keys SET last_used_at = NOW() WHERE id = $1`;
const DELETE_KEY = `
  DELETE FROM lt_bot_api_keys WHERE id = $1`;
const LIST_BY_USER = `
  SELECT id, name, user_id, scopes, expires_at, last_used_at, created_at, updated_at
  FROM lt_bot_api_keys WHERE user_id = $1 ORDER BY created_at`;
/**
 * Generate a new API key for a bot account.
 * Returns the raw key once — it is never stored in plaintext.
 */
async function generateBotApiKey(name, userId, scopes = [], expiresAt) {
    const rawKey = `${TOKEN_PREFIX}${crypto.randomBytes(32).toString('hex')}`;
    const keyHash = await bcryptjs_1.default.hash(rawKey, 10);
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(INSERT_KEY, [
        name, userId, keyHash, scopes, expiresAt || null,
    ]);
    return { id: rows[0].id, rawKey };
}
/**
 * Validate a raw bot API key.
 * Returns the key record (with user_id) if valid, null otherwise.
 */
async function validateBotApiKey(rawKey) {
    if (!rawKey.startsWith(TOKEN_PREFIX))
        return null;
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(GET_ALL_ACTIVE_KEYS);
    for (const row of rows) {
        if (await bcryptjs_1.default.compare(rawKey, row.key_hash)) {
            await pool.query(UPDATE_LAST_USED, [row.id]);
            const { key_hash, ...record } = row;
            return record;
        }
    }
    return null;
}
/**
 * Revoke (delete) a bot API key by ID.
 */
async function revokeBotApiKey(id) {
    const pool = await (0, db_1.getPool)();
    const result = await pool.query(DELETE_KEY, [id]);
    return (result.rowCount ?? 0) > 0;
}
/**
 * List API keys for a bot account (without hashes).
 */
async function listBotApiKeys(userId) {
    const pool = await (0, db_1.getPool)();
    const { rows } = await pool.query(LIST_BY_USER, [userId]);
    return rows;
}
