package dev.lions.user.manager.client.view;

import dev.lions.user.manager.client.service.SyncServiceClient;
import dev.lions.user.manager.dto.sync.HealthStatusDTO;
import dev.lions.user.manager.dto.sync.SyncResultDTO;
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 org.eclipse.microprofile.rest.client.inject.RestClient;

import java.io.Serializable;
import java.util.logging.Logger;

@Named
@ViewScoped
public class SyncDashboardBean implements Serializable {

    private static final Logger LOGGER = Logger.getLogger(SyncDashboardBean.class.getName());

    @Inject
    @RestClient
    SyncServiceClient syncService;

    private HealthStatusDTO keycloakStatus;
    private String syncMessage;
    private String targetRealm = "lions-user-manager"; // Default realm matches OIDC config

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

    public void checkKeycloakStatus() {
        try {
            this.keycloakStatus = syncService.checkKeycloakHealth();
        } catch (Exception e) {
            LOGGER.severe("Erreur lors de la vérification de l'état de Keycloak: " + e.getMessage());
            this.keycloakStatus = new HealthStatusDTO();
            this.keycloakStatus.setOverallHealthy(false);
            this.keycloakStatus.setErrorMessage("Erreur de connexion: " + e.getMessage());
        }
    }

    public void syncUsers() {
        try {
            SyncResultDTO result = syncService.syncUsers(targetRealm);
            handleSyncResult("Utilisateurs", result);
        } catch (Exception e) {
            LOGGER.severe("Erreur lors de la synchronisation des utilisateurs: " + e.getMessage());
            addMessage(FacesMessage.SEVERITY_ERROR, "Erreur",
                    "Echec de la synchronisation des utilisateurs: " + e.getMessage());
        }
    }

    public void syncRoles() {
        try {
            // Sychronize realm roles
            SyncResultDTO result = syncService.syncRoles(targetRealm, null);
            handleSyncResult("Rôles", result);
        } catch (Exception e) {
            LOGGER.severe("Erreur lors de la synchronisation des rôles: " + e.getMessage());
            addMessage(FacesMessage.SEVERITY_ERROR, "Erreur",
                    "Echec de la synchronisation des rôles: " + e.getMessage());
        }
    }

    private void handleSyncResult(String type, SyncResultDTO result) {
        String msg = result.isSuccess()
                ? "Synchronisation réussie. " + type + " synchronisés : "
                        + ("Utilisateurs".equals(type) ? result.getUsersCount() : result.getRealmRolesCount())
                : result.getErrorMessage();

        if (result.isSuccess()) {
            addMessage(FacesMessage.SEVERITY_INFO, "Succès", msg);
        } else {
            addMessage(FacesMessage.SEVERITY_WARN, "Attention", type + ": " + msg);
        }
        this.syncMessage = msg;
    }

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

    // Getters and Setters
    public HealthStatusDTO getKeycloakStatus() {
        return keycloakStatus;
    }

    public void setKeycloakStatus(HealthStatusDTO keycloakStatus) {
        this.keycloakStatus = keycloakStatus;
    }

    // Convenience methods for view
    public String getKeycloakStatusLabel() {
        return (keycloakStatus != null && keycloakStatus.isOverallHealthy()) ? "UP" : "DOWN";
    }

    public String getKeycloakStatusMessage() {
        if (keycloakStatus == null)
            return "Unknown status";
        if (keycloakStatus.isOverallHealthy())
            return "Keycloak est accessible.";
        return keycloakStatus.getErrorMessage() != null ? keycloakStatus.getErrorMessage() : "Erreur inconnue";
    }

    public String getKeycloakVersion() {
        return (keycloakStatus != null) ? keycloakStatus.getKeycloakVersion() : "N/A";
    }

    public String getSyncMessage() {
        return syncMessage;
    }

    public void setSyncMessage(String syncMessage) {
        this.syncMessage = syncMessage;
    }

    public String getTargetRealm() {
        return targetRealm;
    }

    public void setTargetRealm(String targetRealm) {
        this.targetRealm = targetRealm;
    }
}
