/**
 * Migration Script: Clean up onboarding_documents table.
 *
 * What it does (idempotent — safe to re-run):
 *   1. Drops legacy columns `requestId` and `requestType` (and their indexes).
 *      These were generic catch-alls from when a single documents table routed
 *      across modules. Each module now has its own dedicated documents table
 *      (resignation_documents, termination_documents, constitutional_documents,
 *      relocation_documents), so these columns are dead weight on
 *      onboarding_documents and are not read or written anywhere in code.
 *   2. Adds two indexes the UI actually queries:
 *        - (applicationId, stage)  -> Progress / Documents tab grouping
 *        - documentType            -> EOR auto-link in onboarding.controller.ts
 *
 * What it does NOT do:
 *   - No new "documentName" column. The user-entered document name is sent as
 *     the FormData filename and stored in the existing `fileName` column.
 *   - Does not touch `dealerId` (the Dealer <-> OnboardingDocument association
 *     references it; it stays for future use).
 *
 * Run: npx tsx scripts/migrate-onboarding-documents-cleanup.ts
 */
import 'dotenv/config';
import db from '../src/database/models/index.js';

const TABLE = 'onboarding_documents';

async function migrate() {
    const queryInterface = db.sequelize.getQueryInterface();

    try {
        console.log(`🔄 Cleaning up ${TABLE} ...\n`);
        await db.sequelize.authenticate();

        const tableInfo = await queryInterface.describeTable(TABLE);

        // 1) Drop the index on requestId first (if it exists). Index name depends on
        // how Sequelize/Postgres generated it — try the common variants.
        for (const idxName of [
            `${TABLE}_requestId`,
            `${TABLE}_request_id`,
        ]) {
            try {
                await db.sequelize.query(`DROP INDEX IF EXISTS "${idxName}"`);
                console.log(`✓ Dropped index ${idxName} (if existed)`);
            } catch (err: any) {
                console.log(`- Skipped index ${idxName}: ${err.message}`);
            }
        }

        // 2) Drop the unused columns (idempotent via describeTable check).
        for (const col of ['requestId', 'requestType']) {
            if (tableInfo[col]) {
                console.log(`Dropping column ${col} ...`);
                await queryInterface.removeColumn(TABLE, col);
                console.log(`✓ Dropped column ${col}`);
            } else {
                console.log(`- Column ${col} not present (already cleaned)`);
            }
        }

        // 3) Add useful indexes (idempotent — Postgres IF NOT EXISTS).
        await db.sequelize.query(
            `CREATE INDEX IF NOT EXISTS "${TABLE}_applicationId_stage" ON ${TABLE} ("applicationId", "stage")`
        );
        console.log(`✓ Ensured index ${TABLE}_applicationId_stage`);

        await db.sequelize.query(
            `CREATE INDEX IF NOT EXISTS "${TABLE}_documentType" ON ${TABLE} ("documentType")`
        );
        console.log(`✓ Ensured index ${TABLE}_documentType`);

        console.log('\n✅ Migration completed successfully!');
    } catch (error: any) {
        console.error('\n❌ Migration failed:', error.message);
        if (error.stack) console.error('\nStack Trace:\n', error.stack);
        process.exit(1);
    } finally {
        await db.sequelize.close();
    }
}

migrate();
