/**
 * GST Verification Service
 * Primary: Setu API | Fallback: Mock Data
 */

const axios = require('axios');
const { cacheGet, cacheSet } = require('../cache/redis');
const { verifyGstSetu } = require('./setuGstService');

const STATE_NAMES = {
    '01': 'Jammu & Kashmir', '02': 'Himachal Pradesh', '03': 'Punjab',
    '04': 'Chandigarh', '05': 'Uttarakhand', '06': 'Haryana', '07': 'Delhi',
    '08': 'Rajasthan', '09': 'Uttar Pradesh', '10': 'Bihar', '11': 'Sikkim',
    '12': 'Arunachal Pradesh', '13': 'Nagaland', '14': 'Manipur', '15': 'Mizoram',
    '16': 'Tripura', '17': 'Meghalaya', '18': 'Assam', '19': 'West Bengal',
    '20': 'Jharkhand', '21': 'Odisha', '22': 'Chhattisgarh', '23': 'Madhya Pradesh',
    '24': 'Gujarat', '26': 'Dadra & Nagar Haveli', '27': 'Maharashtra',
    '29': 'Karnataka', '30': 'Goa', '31': 'Lakshadweep', '32': 'Kerala',
    '33': 'Tamil Nadu', '34': 'Puducherry', '35': 'Andaman & Nicobar',
    '36': 'Telangana', '37': 'Andhra Pradesh', '38': 'Ladakh'
};

// Mock data for testing (fallback)
const MOCK_GST_DATA = {
    '27AABCU9603R1ZM': {
        legal_name: 'ULTRATECH CEMENT LIMITED',
        trade_name: 'ULTRATECH CEMENT LIMITED',
        status: 'Active',
        registration_date: '2017-07-01',
        last_updated: '2025-01-15',
        business_type: 'Public Limited Company',
        constitution: 'Public Limited Company',
        address: {
            building: 'B WING, AHURA CENTRE',
            floor: '2ND FLOOR',
            street: 'MAHAKALI CAVES ROAD',
            locality: 'ANDHERI EAST',
            city: 'MUMBAI',
            district: 'Mumbai',
            state: 'Maharashtra',
            pincode: '400093'
        },
        nature_of_business: ['Manufacturer', 'Supplier of Services'],
        filing_status: {
            gstr1: 'Filed',
            gstr3b: 'Filed',
            last_filed_date: '2025-01-10'
        }
    },
    '29AABCT1332L1ZD': {
        legal_name: 'TATA MOTORS LIMITED',
        trade_name: 'TATA MOTORS LIMITED',
        status: 'Active',
        registration_date: '2017-07-01',
        last_updated: '2025-01-10',
        business_type: 'Public Limited Company',
        constitution: 'Public Limited Company',
        address: {
            building: 'TATA MOTORS OFFICE',
            floor: '',
            street: 'HOSUR ROAD',
            locality: 'BOMMASANDRA',
            city: 'BANGALORE',
            district: 'Bangalore Urban',
            state: 'Karnataka',
            pincode: '560099'
        },
        nature_of_business: ['Manufacturer', 'Trader'],
        filing_status: {
            gstr1: 'Filed',
            gstr3b: 'Filed',
            last_filed_date: '2025-01-08'
        }
    },
    '27AAACR5055K1Z5': {
        legal_name: 'RELIANCE INDUSTRIES LIMITED',
        trade_name: 'RELIANCE INDUSTRIES LIMITED',
        status: 'Active',
        registration_date: '2017-07-01',
        last_updated: '2025-01-12',
        business_type: 'Public Limited Company',
        constitution: 'Public Limited Company',
        address: {
            building: 'MAKER CHAMBERS IV',
            floor: '3RD FLOOR',
            street: 'NARIMAN POINT',
            locality: 'NARIMAN POINT',
            city: 'MUMBAI',
            district: 'Mumbai',
            state: 'Maharashtra',
            pincode: '400021'
        },
        nature_of_business: ['Manufacturer', 'Trader', 'Supplier of Services'],
        filing_status: {
            gstr1: 'Filed',
            gstr3b: 'Filed',
            last_filed_date: '2025-01-11'
        }
    }
};

async function verifyGSTIN(gstin) {
    try {
        const cacheKey = `gst:${gstin}`;
        const cached = await cacheGet(cacheKey);
        if (cached) {
            console.log(`📦 GSTIN ${gstin} found in cache`);
            return { success: true, source: cached.source || 'CACHE', data: cached };
        }

        // 1. PRIMARY: Try Setu API first
        try {
            const setuResult = await verifyGstSetu(gstin);

            if (setuResult.success) {
                const stateCode = gstin.substring(0, 2);
                const d = setuResult.data;

                // Map Setu's nested response structure
                const data = {
                    gstin: gstin,
                    legal_name: d.company?.name || d.legal_name,
                    trade_name: d.company?.tradeName || d.trade_name,
                    status: d.company?.status || d.status || 'Active',
                    registration_date: d.gst?.registrationDate || d.registration_date,
                    business_type: d.company?.type || d.business_type,
                    constitution: d.company?.constitutionOfBusiness || d.constitution,
                    tax_payer_type: d.company?.taxPayerType,
                    state: STATE_NAMES[stateCode] || d.address?.principle?.stateCode || d.state,
                    state_code: stateCode,
                    pan: gstin.substring(2, 12),
                    address: {
                        building: d.address?.principle?.buildingName || '',
                        building_number: d.address?.principle?.buildingNumber || '',
                        floor: d.address?.principle?.floorNo || '',
                        street: d.address?.principle?.street || '',
                        locality: d.address?.principle?.location || '',
                        city: d.address?.principle?.city || '',
                        district: d.address?.principle?.district || '',
                        state: d.address?.principle?.stateCode || '',
                        pincode: d.address?.principle?.pinCode || ''
                    },
                    jurisdiction: d.jurisdiction || {},
                    source: 'SETU_API'
                };

                // Cache the successful result for 24 hours
                await cacheSet(cacheKey, data, 86400);
                return { success: true, source: 'SETU_API', data };
            }
        } catch (setuError) {
            // Log the Setu error and fall back to mock data
            console.log(`🔄 Switching to mock/local GST data lookup...`);
        }

        // 2. FALLBACK: Mock data for testing
        const mockData = MOCK_GST_DATA[gstin];

        if (mockData) {
            const stateCode = gstin.substring(0, 2);
            const data = {
                gstin,
                ...mockData,
                state: STATE_NAMES[stateCode] || mockData.address.state,
                state_code: stateCode,
                pan: gstin.substring(2, 12),
                source: 'LOCAL_MOCK'
            };

            await cacheSet(cacheKey, data, 86400);
            console.log(`✅ Mock data verification successful for GSTIN: ${gstin}`);
            return { success: true, source: 'LOCAL_MOCK', data };
        } else {
            return { success: false, statusCode: 404, errorCode: 'GSTIN_NOT_FOUND', message: 'GSTIN not found in any verification source' };
        }

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

function formatGSTData(gstin, d) {
    return {
        gstin,
        legal_name: d.legal_name || d.lgnm,
        trade_name: d.trade_name || d.tradeNam,
        status: d.status || d.sts,
        registration_date: d.registration_date || d.rgdt,
        last_updated: d.last_update || d.lstupdt,
        business_type: d.business_type || d.ctb,
        constitution: d.constitution || d.ctj,
        state: d.state || STATE_NAMES[gstin.substring(0, 2)],
        state_code: gstin.substring(0, 2),
        pan: gstin.substring(2, 12),
        address: {
            building: d.address?.bno || d.pradr?.addr?.bno || '',
            floor: d.address?.flno || d.pradr?.addr?.flno || '',
            street: d.address?.st || d.pradr?.addr?.st || '',
            locality: d.address?.loc || d.pradr?.addr?.loc || '',
            city: d.address?.city || d.pradr?.addr?.city || '',
            district: d.address?.dst || d.pradr?.addr?.dst || '',
            state: d.address?.stcd || d.pradr?.addr?.stcd || '',
            pincode: d.address?.pncd || d.pradr?.addr?.pncd || ''
        },
        nature_of_business: d.nature_of_business || d.nba || [],
        filing_status: {
            gstr1: d.filing_status?.gstr1 || 'Unknown',
            gstr3b: d.filing_status?.gstr3b || 'Unknown',
            last_filed_date: d.filing_status?.last_filed || null
        }
    };
}

module.exports = { verifyGSTIN };
