package dev.lions.unionflow.client.view;

import dev.lions.unionflow.client.api.dto.PispiReadinessDto;
import dev.lions.unionflow.client.service.PispiReadinessRestClient;
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 d'inspection PI-SPI Readiness (Sprint 8 ⇄ P1-NEW-15).
 *
 * @since 2026-04-25 (Sprint 8)
 */
@Named
@ViewScoped
public class PispiReadinessBean implements Serializable {

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

  @Inject @RestClient
  PispiReadinessRestClient client;

  private PispiReadinessDto readiness;
  private String erreur;

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

  public void rafraichir() {
    erreur = null;
    try {
      readiness = client.getReadiness();
      LOG.infof("PI-SPI readiness chargé : %s (%d blocking, %d warnings)",
          readiness.globalStatus(),
          readiness.blockingIssues() == null ? 0 : readiness.blockingIssues().size(),
          readiness.warnings() == null ? 0 : readiness.warnings().size());
    } catch (jakarta.ws.rs.WebApplicationException wae) {
      // Backend renvoie 503 quand BLOCKED — on récupère quand même le body
      try {
        readiness = wae.getResponse().readEntity(PispiReadinessDto.class);
        LOG.infof("PI-SPI readiness BLOCKED — body décodé");
      } catch (Exception parseEx) {
        handleError("Décodage réponse readiness échoué", parseEx);
        readiness = null;
      }
    } catch (Exception e) {
      handleError("Chargement PI-SPI readiness échoué", e);
      readiness = null;
    }
  }

  public String getCouleurStatus() {
    if (readiness == null) return "secondary";
    return switch (readiness.globalStatus()) {
      case "READY" -> "success";
      case "DEGRADED" -> "warning";
      case "BLOCKED" -> "danger";
      default -> "secondary";
    };
  }

  public String getCouleurCheck(String severity, String status) {
    if ("PASS".equals(status)) return "success";
    return "BLOCKING".equals(severity) ? "danger" : "warning";
  }

  private void handleError(String summary, Exception e) {
    LOG.warnf("%s : %s", summary, e.getMessage());
    erreur = summary + " — " + e.getMessage();
    FacesContext.getCurrentInstance().addMessage(null,
        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erreur", erreur));
  }

  public PispiReadinessDto getReadiness() { return readiness; }
  public String getErreur() { return erreur; }
}
