/**
 * Add currency column to deposits table
 * Run with: node fix-deposits-currency.js
 */

require('dotenv').config();
const mysql = require('mysql2/promise');

async function fixDepositsTable() {
    console.log('\n🔧 Adding currency column to deposits table\n');
    console.log('='.repeat(60));

    let connection;

    try {
        connection = await mysql.createConnection({
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME,
            port: process.env.DB_PORT
        });

        console.log('✅ Connected to database\n');

        // Check if currency column exists
        const [columns] = await connection.execute(`
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'deposits' AND COLUMN_NAME = 'currency'
        `, [process.env.DB_NAME]);

        if (columns.length > 0) {
            console.log('✅ Currency column already exists!\n');
        } else {
            console.log('🔄 Adding currency column...\n');

            await connection.execute(`
                ALTER TABLE deposits
                ADD COLUMN currency VARCHAR(10) DEFAULT 'NGN' AFTER amount_credited
            `);

            console.log('✅ Currency column added successfully!\n');
        }

        // Verify the fix
        console.log('🔄 Testing deposit insert...\n');

        const [testInsert] = await connection.execute(`
            INSERT INTO deposits (
                user_id,
                payment_method_id,
                reference,
                amount,
                fee,
                amount_credited,
                currency,
                status,
                expires_at,
                created_at,
                updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, 'NGN', 'pending', DATE_ADD(NOW(), INTERVAL 30 MINUTE), NOW(), NOW())
        `, [1, 9, `TEST_FIX_${Date.now()}`, 1000, 15, 985]);

        const testDepositId = testInsert.insertId;
        console.log('✅ Test deposit created successfully!');
        console.log('   Deposit ID:', testDepositId);

        // Clean up
        await connection.execute('DELETE FROM deposits WHERE id = ?', [testDepositId]);
        console.log('✅ Test deposit cleaned up\n');

        console.log('='.repeat(60));
        console.log('✅ Fix complete! Deposit initialization should now work.\n');

    } catch (error) {
        console.error('\n❌ Error:', error.message);
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

// Run fix
fixDepositsTable();
