package dev.lions.components;

import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.validation.constraints.NotBlank;

import java.io.Serial;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.ResourceBundle;

/**
 * Composant gérant l'affichage des notifications dans l'interface utilisateur.
 */
@Slf4j
@Named
@ViewScoped
public class NotificationComponent implements Serializable {

  @Serial
  private static final long serialVersionUID = 1L;
  private static final String MESSAGE_BUNDLE = "messages";

  @Inject
  FacesContext facesContext;

  @Inject
  transient ResourceBundle messageBundle;

  /**
   * Affiche un message de succès.
   */
  public void showSuccess(@NotBlank String key) {
    log.debug("Affichage message succès: {}", key);
    addMessage(FacesMessage.SEVERITY_INFO,
               getMessage(key + ".title", "Succès"),
               getMessage(key + ".detail"));
  }

  /**
   * Affiche un message d'erreur.
   */
  public void showError(@NotBlank String key) {
    log.debug("Affichage message erreur: {}", key);
    addMessage(FacesMessage.SEVERITY_ERROR,
               getMessage(key + ".title", "Erreur"),
               getMessage(key + ".detail"));
  }

  /**
   * Affiche un message d'avertissement.
   */
  public void showWarning(@NotBlank String key) {
    log.debug("Affichage message avertissement: {}", key);
    addMessage(FacesMessage.SEVERITY_WARN,
               getMessage(key + ".title", "Attention"),
               getMessage(key + ".detail"));
  }

  /**
   * Récupère un message localisé avec fallback.
   */
  private String getMessage(String key, String defaultValue) {
    try {
      return messageBundle.getString(key);
    } catch (Exception e) {
      log.warn("Message non trouvé: {}", key);
      return defaultValue;
    }
  }

  private String getMessage(String key) {
    return getMessage(key, key);
  }

  private void addMessage(FacesMessage.Severity severity, String summary, String detail) {
    facesContext.addMessage(null, new FacesMessage(severity, summary, detail));
    log.debug("Message ajouté: {} - {}", summary, detail);
  }
}