/**
 * Bank Account Verification Route
 * Verifies bank account and returns holder details
 */

const express = require('express');
const router = express.Router();
const { authenticateApiKey } = require('../middleware/auth');
const { rateLimit } = require('../middleware/rateLimit');
const { verifyBankAccount } = require('../services/bankService');
const { logApiCall } = require('../services/analytics');

router.use(authenticateApiKey);
router.use(rateLimit);

router.post('/verify', async (req, res, next) => {
    const startTime = Date.now();
    let success = false;

    try {
        const { account_number, ifsc, name } = req.body;

        if (!account_number || !ifsc) {
            return res.status(400).json({
                success: false,
                error: { code: 'MISSING_FIELDS', message: 'Account number and IFSC are required' }
            });
        }

        // Validate IFSC format
        const ifscRegex = /^[A-Z]{4}0[A-Z0-9]{6}$/;
        if (!ifscRegex.test(ifsc.toUpperCase())) {
            return res.status(400).json({
                success: false,
                error: { code: 'INVALID_IFSC', message: 'Invalid IFSC format' }
            });
        }

        // Validate account number (basic check: 9-18 digits)
        if (!/^\d{9,18}$/.test(account_number)) {
            return res.status(400).json({
                success: false,
                error: { code: 'INVALID_ACCOUNT', message: 'Account number must be 9-18 digits' }
            });
        }

        const result = await verifyBankAccount(account_number, ifsc.toUpperCase(), name);

        if (!result.success) {
            return res.status(result.statusCode || 500).json({
                success: false,
                error: { code: result.errorCode, message: result.message }
            });
        }

        success = true;

        res.json({
            success: true,
            data: result.data,
            meta: {
                request_id: `req_bank_${Date.now()}`,
                credits_used: 2, // Bank verification costs 2 credits
                credits_remaining: req.user.remaining - 2
            }
        });

    } catch (error) {
        next(error);
    } finally {
        await logApiCall({
            userId: req.user.id,
            apiKeyId: req.user.apiKeyId,
            endpoint: '/v1/bank/verify',
            method: 'POST',
            params: { account_number: req.body?.account_number, ifsc: req.body?.ifsc },
            status: success ? 200 : 500,
            duration: Date.now() - startTime,
            success,
            isTestKey: req.user.isTestKey
        });
    }
});

module.exports = router;
