package com.honey.honey.service;

import com.honey.honey.config.LocaleConfig;
import com.honey.honey.model.UserA;
import com.honey.honey.repository.UserARepository;
import com.honey.honey.security.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import java.util.Locale;
import java.util.Optional;

/**
 * Service for localization and message retrieval.
 * Gets user's language from UserContext and provides localized messages.
 */
@Service
@RequiredArgsConstructor
public class LocalizationService {

    private final MessageSource messageSource;
    private final UserARepository userARepository;

    /**
     * Gets the current user's locale based on their languageCode.
     * Falls back to English if user not found or languageCode is invalid.
     */
    public Locale getCurrentUserLocale() {
        try {
            UserA user = UserContext.get();
            if (user != null && user.getLanguageCode() != null) {
                return LocaleConfig.languageCodeToLocale(user.getLanguageCode());
            }
        } catch (Exception e) {
            // UserContext might not be available in all contexts (e.g., scheduled tasks)
            // Fall back to English
        }
        return Locale.ENGLISH;
    }

    /**
     * Gets a localized message for the current user.
     * 
     * @param code Message code (e.g., "error.code")
     * @param args Optional arguments for message formatting
     * @return Localized message string
     */
    public String getMessage(String code, Object... args) {
        Locale locale = getCurrentUserLocale();
        return messageSource.getMessage(code, args, code, locale);
    }

    /**
     * Gets a localized message for a specific user by userId.
     * 
     * @param userId User ID
     * @param code Message code
     * @param args Optional arguments for message formatting
     * @return Localized message string
     */
    public String getMessageForUser(Integer userId, String code, Object... args) {
        Locale locale = Locale.ENGLISH; // Default
        Optional<UserA> userOpt = userARepository.findById(userId);
        if (userOpt.isPresent() && userOpt.get().getLanguageCode() != null) {
            locale = LocaleConfig.languageCodeToLocale(userOpt.get().getLanguageCode());
        }
        return messageSource.getMessage(code, args, code, locale);
    }

    /**
     * Gets a localized message for a specific locale.
     * 
     * @param locale Locale to use
     * @param code Message code
     * @param args Optional arguments for message formatting
     * @return Localized message string
     */
    public String getMessage(Locale locale, String code, Object... args) {
        return messageSource.getMessage(code, args, code, locale);
    }
}


