/**
 * Import comprehensive IFSC data from Razorpay API
 * This script fetches IFSC codes for major banks and imports them to the database
 */

const axios = require('axios');
const { Pool } = require('pg');

const pool = new Pool({
    connectionString: process.env.DATABASE_URL || 'postgresql://postgres:fXlNbqBpxhgchmrvPtlMKgwttWVdMDlO@shuttle.proxy.rlwy.net:23879/railway'
});

// Major Indian banks with their IFSC prefixes
const BANK_PREFIXES = [
    { prefix: 'SBIN', name: 'State Bank of India', count: 100 },
    { prefix: 'HDFC', name: 'HDFC Bank', count: 100 },
    { prefix: 'ICIC', name: 'ICICI Bank', count: 100 },
    { prefix: 'KKBK', name: 'Kotak Mahindra Bank', count: 50 },
    { prefix: 'UTIB', name: 'Axis Bank', count: 50 },
    { prefix: 'PUNB', name: 'Punjab National Bank', count: 50 },
    { prefix: 'BARB', name: 'Bank of Baroda', count: 50 },
    { prefix: 'CNRB', name: 'Canara Bank', count: 50 },
    { prefix: 'UBIN', name: 'Union Bank of India', count: 50 },
    { prefix: 'IOBA', name: 'Indian Overseas Bank', count: 30 },
    { prefix: 'IDIB', name: 'Indian Bank', count: 30 },
    { prefix: 'BKID', name: 'Bank of India', count: 30 },
    { prefix: 'CBIN', name: 'Central Bank of India', count: 30 },
    { prefix: 'YESB', name: 'Yes Bank', count: 30 },
    { prefix: 'INDB', name: 'IndusInd Bank', count: 30 },
    { prefix: 'FDRL', name: 'Federal Bank', count: 30 },
    { prefix: 'KVBL', name: 'Karur Vysya Bank', count: 20 },
    { prefix: 'TMBL', name: 'Tamilnad Mercantile Bank', count: 20 },
    { prefix: 'RATN', name: 'RBL Bank', count: 20 },
    { prefix: 'IDFB', name: 'IDFC First Bank', count: 20 },
];

async function fetchAndInsertIFSC(prefix, bankName, count) {
    const inserted = [];
    const failed = [];

    // Generate IFSC codes to try
    for (let i = 0; i <= count; i++) {
        const ifsc = `${prefix}${String(i).padStart(7, '0')}`;

        try {
            const response = await axios.get(`https://ifsc.razorpay.com/${ifsc}`, { timeout: 5000 });
            const data = response.data;

            // Insert into database
            await pool.query(
                `INSERT INTO ifsc_codes (ifsc, bank_name, branch, address, city, district, state, contact, upi_enabled, rtgs_enabled, neft_enabled, imps_enabled, micr_code, swift_code, updated_at)
                 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, NOW())
                 ON CONFLICT (ifsc) DO UPDATE SET 
                 bank_name = EXCLUDED.bank_name, 
                 branch = EXCLUDED.branch,
                 address = EXCLUDED.address,
                 city = EXCLUDED.city,
                 updated_at = NOW()`,
                [
                    ifsc,
                    bankName,
                    data.BRANCH || '',
                    data.ADDRESS || '',
                    data.CITY || '',
                    data.DISTRICT || '',
                    data.STATE || '',
                    data.CONTACT || '',
                    data.UPI || false,
                    data.RTGS || false,
                    data.NEFT || false,
                    data.IMPS || false,
                    data.MICR || '',
                    data.SWIFT || ''
                ]
            );

            inserted.push(ifsc);
            process.stdout.write(`✅ ${ifsc} `);
        } catch (error) {
            if (error.response && error.response.status === 404) {
                // IFSC doesn't exist, skip
            } else {
                failed.push(ifsc);
            }
        }

        // Small delay to not overwhelm the API
        await new Promise(resolve => setTimeout(resolve, 100));
    }

    return { inserted: inserted.length, failed: failed.length };
}

async function main() {
    console.log('🚀 Starting comprehensive IFSC import...\n');

    let totalInserted = 0;

    for (const bank of BANK_PREFIXES) {
        console.log(`\n📦 Fetching ${bank.name} (${bank.prefix})...`);
        const result = await fetchAndInsertIFSC(bank.prefix, bank.name, bank.count);
        totalInserted += result.inserted;
        console.log(`\n   ✅ Inserted: ${result.inserted} codes`);
    }

    console.log(`\n==================================================`);
    console.log(`🎉 Total IFSC codes imported: ${totalInserted}`);
    console.log(`==================================================\n`);

    await pool.end();
}

main().catch(console.error);
