/**
 * Apply a manual SQL migration file to the configured database.
 *
 * Usage:
 *   npx tsx scripts/maint/_run-manual-migration.ts <filename.sql>
 *
 * Only runs the statements under the "-- UP" marker (stops at "-- DOWN").
 * Each statement is executed separately so a syntax error in one
 * doesn't leave the migration half-applied silently — the script
 * exits non-zero on the first failure.
 *
 * Local-only helper. Not part of the smoke runner.
 */
import { PrismaClient } from '@prisma/client';
import fs from 'fs';
import path from 'path';

const prisma = new PrismaClient();

function extractUpSql(content: string): string[] {
    // Find everything between `-- UP` and `-- DOWN`
    const upMatch = content.match(/--\s*=+\s*\n--\s*UP\s*\n--\s*=+\s*([\s\S]*?)(--\s*=+\s*\n--\s*DOWN|$)/i);
    if (!upMatch) {
        throw new Error('Could not find UP section in migration file');
    }
    const upBody = upMatch[1];
    // Split on `;` followed by newline; drop empty / comment-only entries.
    return upBody
        .split(/;\s*\n/)
        .map((s) => s.trim())
        .filter((s) => s.length > 0 && !s.match(/^(--|\s*$)/));
}

async function main() {
    const file = process.argv[2];
    if (!file) {
        console.error('Usage: npx tsx scripts/maint/_run-manual-migration.ts <filename.sql>');
        process.exit(1);
    }
    const full = path.resolve(__dirname, '..', '..', 'prisma', 'migrations', 'manual', file);
    if (!fs.existsSync(full)) {
        console.error(`Not found: ${full}`);
        process.exit(1);
    }
    const content = fs.readFileSync(full, 'utf8');
    const statements = extractUpSql(content);
    console.log(`Loaded ${statements.length} UP statement(s) from ${file}:`);
    for (let i = 0; i < statements.length; i++) {
        const s = statements[i];
        // Show first line + length, not the full SQL — keeps the
        // transcript free of identifier dumps for sensitive schemas.
        const firstLine = s.split('\n')[0].slice(0, 100);
        console.log(`  [${i + 1}] ${firstLine}${s.length > 100 ? '...' : ''}`);
    }
    console.log('Executing...');
    for (let i = 0; i < statements.length; i++) {
        const s = statements[i];
        try {
            const res = await prisma.$executeRawUnsafe(s);
            console.log(`  [${i + 1}] OK (rows affected: ${res})`);
        } catch (err) {
            console.error(`  [${i + 1}] FAILED: ${err instanceof Error ? err.message : err}`);
            process.exit(1);
        }
    }
    console.log('Migration complete.');
}

main().finally(() => prisma.$disconnect());
