package fr.titionfire.ffsaf.utils;

import io.quarkus.security.identity.SecurityIdentity;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.jwt.JsonWebToken;

import java.util.Set;

@RequestScoped
public class SecurityCtx {
    @Inject
    JsonWebToken idToken;

    @Inject
    SecurityIdentity securityIdentity;

    public Set<String> getRoles() {
        return securityIdentity.getRoles();
    }

    public String getSubject() {
        if (idToken == null)
            return null;
        return idToken.getSubject();
    }

    public boolean roleHas(String role) {
        if (role == null)
            return false;
        return securityIdentity.getRoles().contains(role);
    }

    public boolean isClubAdmin() {
        return this.roleHas("club_president") || this.roleHas("club_respo_intra")
                || this.roleHas("club_secretaire") || this.roleHas("club_tresorier");
    }

    public boolean isInClubGroup(long id) {
        if (idToken == null || idToken.getClaim("user_groups") == null)
            return false;

        if (idToken.getClaim("user_groups") instanceof Iterable<?>) {
            for (Object str : (Iterable<?>) idToken.getClaim("user_groups")) {
                if (str.toString().substring(1, str.toString().length() - 1).startsWith("/club/" + id + "-"))
                    return true;
            }
        }
        return false;
    }

    public boolean contains(String string) {
        if (idToken.getClaim("user_groups") instanceof Iterable<?>) {
            for (Object str : (Iterable<?>) idToken.getClaim("user_groups")) {
                if (str.toString().substring(1, str.toString().length() - 1).contains(string))
                    return true;
            }
        }
        return false;
    }
}
