"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runPostgresEvalDenormMigrations = runPostgresEvalDenormMigrations;
const node_child_process_1 = require("node:child_process");
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const logger_1 = __importDefault(require("../../../logger"));
async function verifyDenormTables() {
    const db = (0, database_1.getDb)();
    const rows = await db.execute((0, drizzle_orm_1.sql) `
    SELECT table_name
    FROM information_schema.tables
    WHERE table_schema = 'public'
      AND table_name IN ('eval_results_analytics', 'eval_result_components')
    ORDER BY table_name
  `);
    const names = Array.isArray(rows)
        ? rows.map((r) => String(r.table_name ?? ''))
        : Array.isArray(rows.rows)
            ? rows.rows.map((r) => String(r.table_name ?? ''))
            : [];
    const required = ['eval_result_components', 'eval_results_analytics'];
    const missing = required.filter((t) => !names.includes(t));
    if (missing.length > 0) {
        throw new Error(`Missing Postgres denorm tables: ${missing.join(', ')}`);
    }
    const colRows = await db.execute((0, drizzle_orm_1.sql) `
    SELECT table_name, column_name
    FROM information_schema.columns
    WHERE table_schema = 'public'
      AND table_name IN ('eval_results_analytics', 'eval_result_components')
      AND column_name = 'trace_ids'
  `);
    const colList = Array.isArray(colRows)
        ? colRows
        : (colRows.rows ?? []);
    if (colList.length < 2) {
        throw new Error('trace_ids column missing on one or both denorm tables (run drizzle 0023 if needed)');
    }
    return names;
}
/**
 * Postgres eval denorm DDL: runs pending Drizzle migrations, then verifies denorm tables.
 */
async function runPostgresEvalDenormMigrations(options) {
    const verifyOnly = options?.verifyOnly === true;
    let migrated = false;
    if (!verifyOnly) {
        logger_1.default.info('Postgres eval-denorm migrate: running npm run db:migrate');
        (0, node_child_process_1.execSync)('npm run db:migrate', { stdio: 'pipe', cwd: process.cwd() });
        migrated = true;
    }
    const tables = await verifyDenormTables();
    return { verifyOnly, migrated, tables };
}
//# sourceMappingURL=postgresEvalDenormMigrations.js.map