/**
 * AYSA Service Type Helper
 * Implements service type determination and VAT calculation logic matching the backend
 * Based on StaticValuesController.cs logic
 */

var AysaServiceTypeHelper = {
    
    // EU Countries list matching backend
    euCountries: [
        'Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czechia',
        'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland',
        'Italy', 'Latvia', 'Lithuania', 'Malta', 'Netherlands', 'Poland',
        'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden'
    ],
    
    // All supported countries from backend
    allCountries: [
        'Albania', 'Algeria', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria', 
        'Azerbaijan', 'Bahrain', 'Bangladesh', 'Belgium', 'Bolivia', 'Bosnia and Herzegovina', 
        'Brazil', 'Bulgaria', 'Myanmar (Burma)', 'Cambodia', 'Cameroon', 'Canada', 'Chile', 
        'Colombia', 'Costa Rica', 'Croatia', 'Cyprus', 'Czechia', 'Denmark', 'Ecuador', 
        'Egypt', 'El Salvador', 'Estonia', 'Finland', 'France', 'Germany', 'Ghana', 'Greece', 
        'Guatemala', 'Hong Kong', 'Hungary', 'India', 'Indonesia', 'Ireland', 'Israel', 
        'Italy', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'South Korea', 'Latvia', 
        'Lithuania', 'Malaysia', 'Malta', 'Mexico', 'Monaco', 'Moldova', 'Morocco', 
        'Netherlands', 'New Zealand', 'Nicaragua', 'Nigeria', 'Norway', 'Pakistan', 
        'Panama', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Romania', 
        'Saudi Arabia', 'Senegal', 'Serbia', 'Singapore', 'Slovakia', 'Slovenia', 
        'South Africa', 'Spain', 'Sri Lanka', 'Sweden', 'Switzerland', 'Taiwan', 'Thailand', 
        'Tunisia', 'Turkiye', 'Ukraine', 'North Macedonia', 'United Arab Emirates', 
        'United Kingdom', 'United States', 'Burkina Faso', 'Uruguay', 'Venezuela', 'Vietnam',
        'Cote d\'Ivoire'
    ],
    
    /**
     * Determine service type based on country and client type
     * Matches backend GetServiceType logic
     * 
     * @param {string} country - Country name
     * @param {boolean} isCompany - Whether the client is a company (B2B) or individual (B2C)
     * @returns {string} Service type description in Romanian
     */
    getServiceType: function(country, isCompany) {
        if (!country || typeof country !== 'string') {
            throw new Error('Country parameter is required and must be a string.');
        }
        
        let serviceType;
        
        if (country === 'Romania') {
            serviceType = 'Servicii prestate în România';
        } else if (this.euCountries.includes(country)) {
            if (isCompany) {
                serviceType = 'Servicii prestate în UE (client B2B)';
            } else {
                serviceType = 'Servicii electronice, telecom, difuzare (client B2C în UE)';
            }
        } else if (this.allCountries.includes(country)) {
            if (isCompany) {
                serviceType = 'Servicii prestate în afara UE (B2B)';
            } else {
                serviceType = 'Servicii electronice, telecom, difuzare (client B2C în afara UE)';
            }
        } else {
            throw new Error('Invalid country: ' + country);
        }
        
        return serviceType;
    },
    
    /**
     * Get VAT rate based on service type and country
     * This would typically call the backend API, but provides fallback logic
     * 
     * @param {string} serviceType - Service type from getServiceType
     * @param {string} country - Country name
     * @returns {number} VAT rate as decimal (e.g., 0.19 for 19%)
     */
    getVatByServiceType: function(serviceType, country) {
        // Default VAT rates based on common patterns
        // In production, this should call the backend API
        
        if (country === 'Romania') {
            return 0.19; // 19% VAT for Romania
        }
        
        if (serviceType.includes('UE (client B2B)')) {
            return 0.0; // B2B in EU typically has reverse charge (0% VAT)
        }
        
        if (serviceType.includes('UE (client B2C)') || serviceType.includes('client B2C în UE')) {
            return 0.19; // Standard EU VAT rate (varies by country, 19% as default)
        }
        
        if (serviceType.includes('afara UE')) {
            return 0.0; // Outside EU typically 0% VAT
        }
        
        return 0.19; // Default fallback
    },
    
    /**
     * Get VAT rate from backend API
     * 
     * @returns {Promise<number>} VAT rate as decimal
     */
    getVatFromAPI: async function() {
        try {
            const apiBaseUrl = ((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '');
            const response = await fetch(`${apiBaseUrl}/api/StaticValues/get-vat`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + (this.getAuthToken ? this.getAuthToken() : ''),
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (response.ok) {
                const vatPercentage = await response.json();
                return vatPercentage / 100; // Convert percentage to decimal
            }
        } catch (error) {
            console.error('Error getting VAT from API:', error);
        }
        
        // Fallback to default rate
        return 0.19;
    },
    
    /**
     * Check if a country is in the EU
     * 
     * @param {string} country - Country name
     * @returns {boolean} True if country is in EU
     */
    isEUCountry: function(country) {
        return this.euCountries.includes(country);
    },
    
    /**
     * Check if a country is supported
     * 
     * @param {string} country - Country name
     * @returns {boolean} True if country is supported
     */
    isSupportedCountry: function(country) {
        return this.allCountries.includes(country);
    },
    
    /**
     * Calculate price with VAT
     * 
     * @param {number} basePrice - Base price without VAT
     * @param {number} vatRate - VAT rate as decimal (e.g., 0.19 for 19%)
     * @returns {number} Price including VAT
     */
    calculatePriceWithVAT: function(basePrice, vatRate) {
        if (typeof basePrice !== 'number' || typeof vatRate !== 'number') {
            throw new Error('Base price and VAT rate must be numbers');
        }
        
        const vatAmount = basePrice * vatRate;
        return Math.round((basePrice + vatAmount) * 100) / 100; // Round to 2 decimal places
    },
    
    /**
     * Get comprehensive service information for a country and client type
     * 
     * @param {string} country - Country name
     * @param {boolean} isCompany - Whether client is a company
     * @returns {object} Service information object
     */
    getServiceInfo: function(country, isCompany) {
        const serviceType = this.getServiceType(country, isCompany);
        const vatRate = this.getVatByServiceType(serviceType, country);
        
        return {
            country: country,
            isCompany: isCompany,
            serviceType: serviceType,
            vatRate: vatRate,
            vatPercentage: Math.round(vatRate * 100),
            isEU: this.isEUCountry(country),
            isSupported: this.isSupportedCountry(country)
        };
    }
};

// Make it available globally
window.AysaServiceTypeHelper = AysaServiceTypeHelper;
