package com.imprimelibros.erp.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Configuration
public class InternationalizationConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.forLanguageTag("es-ES")); // idioma por defecto
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang"); // parámetro ?lang=en, ?lang=es
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

    @Bean
    public MessageSource messageSource() throws IOException {
        ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:i18n/*.properties");

        // Extraer nombres base sin sufijos de idioma
        Set<String> basenames = Arrays.stream(resources)
                .map(res -> {
                    try {
                        String uri = Objects.requireNonNull(res.getURI()).toString();
                        // Ejemplo: file:/.../i18n/login_en.properties
                        String path = uri.substring(uri.indexOf("/i18n/") + 1); // i18n/login_en.properties
                        String base = path.replaceAll("_[a-z]{2}\\.properties$", "") // login.properties
                                          .replaceAll("\\.properties$", "");
                        return "classpath:" + base;
                    } catch (IOException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        source.setBasenames(basenames.toArray(new String[0]));
        source.setDefaultEncoding("UTF-8");

        return source;
    }
}
