package com.honey.honey.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

@Configuration
public class LocaleConfig {

    // Supported languages
    public static final List<String> SUPPORTED_LANGUAGES = Arrays.asList(
        "EN", "RU", "DE", "IT", "NL", "PL", "FR", "ES", "ID", "TR"
    );

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setFallbackToSystemLocale(false);
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.ENGLISH);
        return resolver;
    }

    /**
     * Converts language code (EN, RU, etc.) to Locale.
     */
    public static Locale languageCodeToLocale(String languageCode) {
        if (languageCode == null || languageCode.isEmpty() || "XX".equals(languageCode)) {
            return Locale.ENGLISH;
        }
        
        String upperCode = languageCode.toUpperCase();
        // Handle special cases
        switch (upperCode) {
            case "ID":
                return new Locale("id"); // Indonesian
            default:
                try {
                    return new Locale(upperCode.toLowerCase());
                } catch (Exception e) {
                    return Locale.ENGLISH; // Default fallback
                }
        }
    }
}


