"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 });
exports.migrate = migrate;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const index_1 = require("./index");
const logger_1 = require("../logger");
// Both dev (lib/db/) and build (build/lib/db/) have schemas/ as a sibling.
// In dev it exists naturally; in build it's copied by the build script.
const SCHEMAS_DIR = path.join(__dirname, 'schemas');
async function migrate() {
    const pool = (0, index_1.getPool)();
    // Advisory lock prevents concurrent containers from racing on migrations.
    // Uses a dedicated client so the lock is held for the entire sequence.
    const client = await pool.connect();
    try {
        await client.query('SELECT pg_advisory_lock(8675309)');
        // ensure migration tracking table
        await client.query(`
      CREATE TABLE IF NOT EXISTS lt_migrations (
        id SERIAL PRIMARY KEY,
        name TEXT NOT NULL UNIQUE,
        applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );
    `);
        // find and sort migration files
        const files = fs.readdirSync(SCHEMAS_DIR)
            .filter(f => f.endsWith('.sql'))
            .sort();
        for (const file of files) {
            const { rows } = await client.query('SELECT 1 FROM lt_migrations WHERE name = $1', [file]);
            if (rows.length === 0) {
                const sql = fs.readFileSync(path.join(SCHEMAS_DIR, file), 'utf-8');
                await client.query(sql);
                await client.query('INSERT INTO lt_migrations (name) VALUES ($1)', [file]);
                logger_1.loggerRegistry.info(`[migrate] applied: ${file}`);
            }
        }
    }
    finally {
        // Advisory lock released when client is released (session-scoped),
        // but release explicitly for clarity
        await client.query('SELECT pg_advisory_unlock(8675309)').catch(() => { });
        client.release();
    }
}
// run directly: npx ts-node lib/db/migrate.ts
if (require.main === module) {
    require('dotenv').config();
    migrate()
        .then(() => {
        logger_1.loggerRegistry.info('[migrate] done');
        return (0, index_1.closePool)();
    })
        .catch((err) => {
        logger_1.loggerRegistry.error(`[migrate] failed: ${err}`);
        process.exit(1);
    });
}
