/**
 * Setu API Integration Service
 * Primary verification provider for PAN
 * Documentation: https://docs.setu.co/
 */

const axios = require('axios');

/**
 * Verify PAN using Setu Sandbox API
 * @param {string} panNumber - The PAN number to verify
 * @returns {Promise<Object>} - Verification result with full_name and other details
 * @throws {Error} - Throws if Setu API fails
 */
async function verifyPanSetu(panNumber) {
    const baseUrl = process.env.SETU_BASE_URL;
    const clientId = process.env.SETU_CLIENT_ID;
    const clientSecret = process.env.SETU_CLIENT_SECRET;
    const productInstanceId = process.env.SETU_PRODUCT_INSTANCE_ID;

    // Validate environment variables
    if (!baseUrl || !clientId || !clientSecret || !productInstanceId) {
        throw new Error('Setu API configuration is incomplete. Check environment variables.');
    }

    try {
        const response = await axios.post(
            `${baseUrl}/api/verify/pan`,
            {
                pan: panNumber,
                consent: 'Y',
                reason: 'Verification for user onboarding'
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'x-client-id': clientId,
                    'x-client-secret': clientSecret,
                    'x-product-instance-id': productInstanceId
                },
                timeout: 30000 // 30 second timeout
            }
        );

        // Check if Setu returned a successful verification
        if (response.data && response.data.verification === 'SUCCESS') {
            return {
                success: true,
                source: 'SETU_API',
                data: response.data.data
            };
        }

        // If verification field is not SUCCESS, treat as failure
        throw new Error(response.data?.message || 'PAN verification failed via Setu');

    } catch (error) {
        // Re-throw with more context
        if (error.response) {
            // Setu returned an error response
            const statusCode = error.response.status;
            const errorMessage = error.response.data?.message || error.response.data?.error || 'Unknown Setu API error';
            throw new Error(`Setu API Error (${statusCode}): ${errorMessage}`);
        } else if (error.code === 'ECONNABORTED') {
            throw new Error('Setu API timeout');
        } else {
            throw error;
        }
    }
}

module.exports = { verifyPanSetu };
