/**
 * PAN Verification Route
 * Verifies PAN and returns holder details
 */

const express = require('express');
const router = express.Router();
const { authenticateApiKey } = require('../middleware/auth');
const { rateLimit } = require('../middleware/rateLimit');
const { verifyPAN } = require('../services/panService');
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 { pan, name, dob } = req.body;

        if (!pan) {
            return res.status(400).json({
                success: false,
                error: { code: 'MISSING_PAN', message: 'PAN is required' }
            });
        }

        const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;

        if (!panRegex.test(pan.toUpperCase())) {
            return res.status(400).json({
                success: false,
                error: { code: 'INVALID_PAN', message: 'Invalid PAN format' }
            });
        }

        const result = await verifyPAN(pan.toUpperCase(), name, dob);

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

        success = true;

        res.json({
            success: true,
            data: result.data,
            meta: {
                request_id: `req_pan_${Date.now()}`,
                credits_used: 1,
                credits_remaining: req.user.remaining - 1
            }
        });

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

/**
 * GET /verify/:panNumber
 * Fetch PAN details via URL parameter
 */
router.get('/verify/:panNumber', async (req, res, next) => {
    const startTime = Date.now();
    let success = false;

    try {
        const { panNumber } = req.params;

        if (!panNumber) {
            return res.status(400).json({
                success: false,
                error: { code: 'MISSING_PAN', message: 'PAN is required' }
            });
        }

        const result = await verifyPAN(panNumber.toUpperCase());

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

        success = true;

        res.json({
            success: true,
            data: result.data,
            meta: {
                request_id: `req_pan_${Date.now()}`,
                credits_used: 1,
                credits_remaining: req.user.remaining - 1
            }
        });

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

module.exports = router;
