/**
 * Bank Account Verification Service
 * Mock implementation for testing (replace with real API in production)
 */

const axios = require('axios');
const { cacheGet, cacheSet } = require('../cache/redis');
const { query } = require('../database/connection');

// Mock data for testing
const MOCK_BANK_DATA = {
    '1234567890123': {
        account_exists: true,
        name_at_bank: 'RAHUL SHARMA',
        bank_name: 'HDFC Bank',
        branch: 'Fort Branch'
    },
    '9876543210987': {
        account_exists: true,
        name_at_bank: 'PRIYA PATEL',
        bank_name: 'State Bank of India',
        branch: 'Mumbai Main Branch'
    }
};

async function verifyBankAccount(accountNumber, ifsc, name = null) {
    try {
        // Check if we should use real API or mock
        if (process.env.BANK_PROVIDER_URL && process.env.BANK_PROVIDER_KEY) {
            // Real API call
            const response = await axios.post(
                process.env.BANK_PROVIDER_URL,
                {
                    account_number: accountNumber,
                    ifsc: ifsc,
                    name: name
                },
                {
                    headers: {
                        'Authorization': `Bearer ${process.env.BANK_PROVIDER_KEY}`,
                        'Content-Type': 'application/json'
                    },
                    timeout: 30000
                }
            );

            if (!response.data) {
                return { success: false, statusCode: 500, errorCode: 'VERIFICATION_FAILED', message: 'Verification failed' };
            }

            const d = response.data.data;
            const data = {
                account_number: accountNumber,
                ifsc: ifsc,
                account_exists: d.account_exists || d.valid,
                name_at_bank: d.name_at_bank || d.beneficiary_name,
                bank_name: d.bank_name,
                branch: d.branch
            };

            return addNameMatch({ success: true, data }, name);
        } else {
            // Mock implementation for testing
            const mockData = MOCK_BANK_DATA[accountNumber];

            // Get bank details from IFSC if available
            let bankDetails = { bank_name: 'Unknown Bank', branch: 'Unknown Branch' };
            try {
                const ifscResult = await query('SELECT bank_name, branch FROM ifsc_codes WHERE ifsc = $1', [ifsc.toUpperCase()]);
                if (ifscResult.rows.length > 0) {
                    bankDetails = {
                        bank_name: ifscResult.rows[0].bank_name,
                        branch: ifscResult.rows[0].branch
                    };
                }
            } catch (e) {
                // Ignore IFSC lookup errors
            }

            if (!mockData) {
                // Return account not found for unknown accounts
                return {
                    success: true,
                    data: {
                        account_number: accountNumber,
                        ifsc: ifsc,
                        account_exists: false,
                        name_at_bank: null,
                        name_match: false,
                        name_match_score: 0,
                        bank_name: bankDetails.bank_name,
                        branch: bankDetails.branch
                    }
                };
            }

            const data = {
                account_number: accountNumber,
                ifsc: ifsc,
                account_exists: mockData.account_exists,
                name_at_bank: mockData.name_at_bank,
                bank_name: bankDetails.bank_name || mockData.bank_name,
                branch: bankDetails.branch || mockData.branch
            };

            return addNameMatch({ success: true, data }, name);
        }

    } catch (error) {
        if (error.code === 'ECONNABORTED') {
            return { success: false, statusCode: 504, errorCode: 'PROVIDER_TIMEOUT', message: 'Service timeout' };
        }
        console.error('Bank verification error:', error.message);
        return { success: false, statusCode: 500, errorCode: 'VERIFICATION_FAILED', message: 'Verification failed' };
    }
}

function addNameMatch(result, inputName) {
    if (!result.success || !inputName || !result.data.name_at_bank) {
        if (result.success) {
            result.data.name_match = false;
            result.data.name_match_score = 0;
        }
        return result;
    }

    const registeredName = result.data.name_at_bank.toUpperCase();
    const providedName = inputName.toUpperCase();

    // Simple name matching
    const nameMatch = registeredName === providedName ||
        registeredName.includes(providedName) ||
        providedName.includes(registeredName);

    // Calculate match score
    let matchScore = 0;
    if (nameMatch) {
        matchScore = registeredName === providedName ? 100 : 80;
    } else {
        // Partial matching
        const regWords = registeredName.split(' ');
        const provWords = providedName.split(' ');
        const matches = regWords.filter(w => provWords.includes(w)).length;
        matchScore = Math.round((matches / Math.max(regWords.length, provWords.length)) * 100);
    }

    result.data.name_match = matchScore >= 80;
    result.data.name_match_score = matchScore;

    return result;
}

module.exports = { verifyBankAccount };
