package dev.lions.unionflow.client.view;

import dev.lions.unionflow.client.api.dto.ComplianceSnapshotDto;
import dev.lions.unionflow.client.service.ComplianceDashboardRestClient;
import jakarta.annotation.PostConstruct;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.Serializable;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.logging.Logger;

/**
 * Bean du tableau de bord de conformité (Sprint 8 ⇄ backend P1-NEW-7).
 *
 * <p>Affiche le snapshot de l'organisation active : score global, indicateurs AG/AIRMS/CMU/KYC/UBO,
 * alertes critiques. Refresh manuel par bouton.
 *
 * @since 2026-04-25 (Sprint 8)
 */
@Named
@ViewScoped
public class ConformiteDashboardBean implements Serializable {

  private static final long serialVersionUID = 1L;
  private static final Logger LOG = Logger.getLogger(ConformiteDashboardBean.class);

  @Inject @RestClient
  ComplianceDashboardRestClient client;

  private ComplianceSnapshotDto snapshot;
  private String erreur;

  @PostConstruct
  public void init() {
    rafraichir();
  }

  public void rafraichir() {
    erreur = null;
    try {
      snapshot = client.getSnapshotCurrent();
      LOG.infof("Snapshot conformité chargé : score=%d", snapshot.scoreGlobal());
    } catch (Exception e) {
      LOG.warnf("Échec chargement compliance dashboard : %s", e.getMessage());
      erreur = "Impossible de charger le tableau de bord : " + e.getMessage();
      addMessage(FacesMessage.SEVERITY_ERROR, "Erreur", erreur);
      snapshot = null;
    }
  }

  public String getCouleurScore() {
    if (snapshot == null) return "secondary";
    int s = snapshot.scoreGlobal();
    if (s >= 80) return "success";
    if (s >= 60) return "warning";
    return "danger";
  }

  public boolean hasAlertes() {
    if (snapshot == null) return false;
    return !snapshot.complianceOfficerDesigne()
        || "RETARD".equals(snapshot.agAnnuelle().statut())
        || snapshot.scoreGlobal() < 60;
  }

  private void addMessage(FacesMessage.Severity sev, String summary, String detail) {
    FacesContext.getCurrentInstance().addMessage(null,
        new FacesMessage(sev, summary, detail));
  }

  public ComplianceSnapshotDto getSnapshot() { return snapshot; }
  public String getErreur() { return erreur; }
}
