import axios from 'axios';
import logger from '../utils/logger';

export interface ExternalDealerResponse {
    dealer: string;
    'dealer name': string;
    'item group': string | null;
    'proprietor/Driector Names': string | null;
    gstin: string | null;
    pan: string | null;
    'irn eligibility': string;
    'region id': string | null;
    're state code': string | null;
    're city': string | null;
    'store address': string | null;
    pincode: string | null;
    'dealer email': string | null;
    'dealer phone': string | null;
    parentcode?: string | null;
}

export class DealerExternalService {
    private apiUrl: string;
    private authHeader: string;
    private authToken: string;

    constructor() {
        this.apiUrl = process.env.RE_DEALER_API_URL || 'https://api-uat2.royalenfield.com/DealerMaster';
        this.authHeader = process.env.RE_DEALER_API_AUTH || 'q7WlK9ZpT2JfV8mXc4sB0nYdH6R3aQeU1CjGxL5uPzI=';
        this.authToken = process.env.RE_DEALER_API_TOKEN || 're_c92b9cf291d2be65a1704207aa25352d69432b643e6c9e9a172938c964809f2d';
    }

    /**
     * Fetch dealer information from external Royal Enfield API by dealer code
     * @param dealerCode The code of the dealer to search for
     */
    async getDealerByCode(dealerCode: string): Promise<ExternalDealerResponse | null> {
        try {
            logger.info(`[DealerExternalService] Fetching dealer info for code: ${dealerCode}`);

            const response = await axios.get(this.apiUrl, {
                params: { dealer_code: dealerCode },
                headers: {
                    'auth': this.authHeader,
                    'Authorization': `Bearer ${this.authToken}`
                }
            });

            if (!response.data) {
                logger.warn(`[DealerExternalService] No data returned for dealer code: ${dealerCode}`);
                return null;
            }

            // The API returns an object or array? Based on user request, it looks like a single object
            // but usually these APIs return arrays. Let's handle both just in case.
            const data = Array.isArray(response.data) ? response.data[0] : response.data;

            if (!data || Object.keys(data).length === 0) {
                logger.warn(`[DealerExternalService] Empty dealer data for code: ${dealerCode}`);
                return null;
            }

            // Map the response to the requested format if it's different, 
            // but user's response example seems to be the literal API response structure.
            // We'll return it as is but ensure types match.
            return {
                dealer: data.dealer || dealerCode,
                'dealer name': data['dealer name'] || '',
                'item group': data['item group'] || null,
                'proprietor/Driector Names': data['proprietor/Driector Names'] || null,
                gstin: data.gstin || null,
                pan: data.pan || null,
                'irn eligibility': data['irn eligibility'] || 'no',
                'region id': data['region id'] || null,
                're state code': data['re state code'] || null,
                're city': data['re city'] || null,
                'store address': data['store address'] || null,
                pincode: data.pincode || null,
                'dealer email': data['dealer email'] || null,
                'dealer phone': data['dealer phone'] || null,
                parentcode: data.parentcode || null
            };

        } catch (error) {
            if (axios.isAxiosError(error)) {
                logger.error(`[DealerExternalService] API Error: ${error.response?.status} - ${JSON.stringify(error.response?.data)}`);
            } else {
                logger.error(`[DealerExternalService] Unexpected Error: ${error instanceof Error ? error.message : 'Unknown'}`);
            }
            throw error;
        }
    }
}

export const dealerExternalService = new DealerExternalService();
