package dev.lions.unionflow.client.view;

import dev.lions.unionflow.client.constants.ViewPaths;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Logger;

/**
 * Bean de navigation avec authentification Keycloak OIDC
 * 
 * @author UnionFlow Team
 * @version 2.0
 */
@Named("navigationBean")
@RequestScoped
public class NavigationBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = Logger.getLogger(NavigationBean.class.getName());

    @Inject
    private UserSession userSession;

    public void checkAuthentication() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();

        if (isUserAuthenticated()) {
            // L'utilisateur est connecté, rediriger vers le dashboard approprié
            String dashboardUrl = getDashboardUrlForUserType();
            context.getExternalContext().redirect(
                    context.getExternalContext().getRequestContextPath() + dashboardUrl);
        } else {
            // L'utilisateur n'est pas connecté, rediriger vers la racine qui déclenchera
            // Keycloak
            context.getExternalContext().redirect(
                    context.getExternalContext().getRequestContextPath() + "/");
        }
    }

    public String redirectToLogin() {
        // Redirection vers la racine qui déclenchera automatiquement Keycloak
        return "/?faces-redirect=true";
    }

    public String goToDashboard() {
        if (!isUserAuthenticated()) {
            return redirectToLogin();
        }

        return getDashboardUrlForUserType() + "?faces-redirect=true";
    }

    public String redirectToDashboard() {
        return goToDashboard();
    }

    public String goToProfile() {
        if (!isUserAuthenticated()) {
            return redirectToLogin();
        }

        return ViewPaths.PROFILE + ViewPaths.REDIRECT_SUFFIX;
    }

    public String goToSettings() {
        if (!isUserAuthenticated()) {
            return redirectToLogin();
        }

        if (userSession.isSuperAdmin()) {
            return ViewPaths.SUPER_ADMIN_CONFIGURATION_SYSTEME + ViewPaths.REDIRECT_SUFFIX;
        } else if (userSession.isAdmin()) {
            return ViewPaths.ADMIN_PARAMETRES + ViewPaths.REDIRECT_SUFFIX;
        } else {
            return ViewPaths.MEMBRE_PARAMETRES + ViewPaths.REDIRECT_SUFFIX;
        }
    }

    private boolean isUserAuthenticated() {
        // Avec Keycloak OIDC, UserSession vérifie automatiquement l'authentification
        // via SecurityIdentity
        return userSession != null && userSession.isAuthenticated();
    }

    private String getDashboardUrlForUserType() {
        if (userSession == null || userSession.getTypeCompte() == null) {
            return ViewPaths.DASHBOARD + ".xhtml";
        }

        switch (userSession.getTypeCompte()) {
            case "SUPER_ADMIN":
                return ViewPaths.SUPER_ADMIN_DASHBOARD + ".xhtml";
            case "ADMIN_ORGANISATION":
            case "MODERATEUR":
                return ViewPaths.DASHBOARD + ".xhtml";
            case "MEMBRE_ACTIF":
            case "MEMBRE":
                return ViewPaths.DASHBOARD_MEMBRE + ".xhtml";
            default:
                LOGGER.warning("Type de compte non reconnu: " + userSession.getTypeCompte());
                return ViewPaths.DASHBOARD + ".xhtml";
        }
    }

    public boolean canAccessSuperAdminPages() {
        return isUserAuthenticated() && userSession.isSuperAdmin();
    }

    public boolean canAccessAdminPages() {
        return isUserAuthenticated() && userSession.isAdmin();
    }

    public boolean canAccessMemberPages() {
        return isUserAuthenticated() && userSession.isMembre();
    }

    public String getCurrentPageTitle() {
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();

        if (viewId.contains("dashboard")) {
            return "Tableau de Bord";
        } else if (viewId.contains("membres")) {
            return "Gestion des Membres";
        } else if (viewId.contains("organisation")) {
            return "Gestion des Organisations";
        } else if (viewId.contains("configuration")) {
            return "Configuration";
        } else if (viewId.contains("rapports")) {
            return "Rapports et Statistiques";
        }

        return "UnionFlow";
    }
}
