package fr.titionfire.ffsaf;

import fr.titionfire.ffsaf.domain.service.TradService;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;

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

@Provider
@PreMatching
public class UserInfoProvider implements ContainerRequestFilter {

    private static final List<Locale> SUPPORTED_LANGUAGES = Arrays.asList(
            Locale.FRENCH,
            Locale.ENGLISH
    );

    @Override
    public void filter(ContainerRequestContext requestContext) {
        List<Locale> acceptableLanguages = requestContext.getAcceptableLanguages();
        Locale selectedLocale = findFirstSupportedLanguage(acceptableLanguages);

        if (selectedLocale == null)
            selectedLocale = TradService.fallbackLocale;
        requestContext.setProperty("userLocale", selectedLocale);
    }

    private Locale findFirstSupportedLanguage(List<Locale> acceptableLanguages) {
        for (Locale acceptableLanguage : acceptableLanguages) {
            // Vérifie si la langue est dans la liste des langues supportées
            if (SUPPORTED_LANGUAGES.contains(acceptableLanguage)) {
                return acceptableLanguage;
            }
            // Vérifie aussi par tag de langue (ex: "fr-FR" -> "fr")
            String languageTag = acceptableLanguage.getLanguage();
            for (Locale supportedLanguage : SUPPORTED_LANGUAGES) {
                if (supportedLanguage.getLanguage().equals(languageTag)) {
                    return supportedLanguage;
                }
            }
        }
        return null;
    }
}
