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

const axios = require('axios');

/**
 * Verify GSTIN using Setu Sandbox API
 * @param {string} gstin - The GSTIN to verify
 * @returns {Promise<Object>} - Verification result with business details
 * @throws {Error} - Throws if Setu API fails
 */
async function verifyGstSetu(gstin) {
    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_GST_INSTANCE_ID;

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

    try {
        console.log(`🌐 Attempting Setu GST verification for GSTIN: ${gstin}`);

        const response = await axios.post(
            `${baseUrl}/api/verify/gst`,
            {
                gstin: gstin,
                consent: 'Y',
                reason: 'Vendor verification'
            },
            {
                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 (case-insensitive)
        const verification = response.data?.verification?.toLowerCase();
        if (response.data && (verification === 'success' || response.data.status === 'success')) {
            console.log(`✅ Setu GST verification successful for GSTIN: ${gstin}`);
            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 || 'GST 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';
            console.warn(`⚠️ Setu GST API failed for GSTIN ${gstin}: Setu API Error (${statusCode}): ${errorMessage}`);
            throw new Error(`Setu API Error (${statusCode}): ${errorMessage}`);
        } else if (error.code === 'ECONNABORTED') {
            console.warn(`⚠️ Setu GST API timeout for GSTIN ${gstin}`);
            throw new Error('Setu API timeout');
        } else {
            console.warn(`⚠️ Setu GST API failed for GSTIN ${gstin}: ${error.message}`);
            throw error;
        }
    }
}

module.exports = { verifyGstSetu };
