package tech.easyflow.system.entity.vo;

import java.math.BigInteger;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public class RoleCategoryAccessSnapshot {

    private final String resourceType;
    private final BigInteger accountId;
    private final boolean superAdmin;
    private final boolean allAccess;
    private final Set<BigInteger> categoryIds;

    public RoleCategoryAccessSnapshot(String resourceType,
                                      BigInteger accountId,
                                      boolean superAdmin,
                                      boolean allAccess,
                                      Set<BigInteger> categoryIds) {
        this.resourceType = resourceType;
        this.accountId = accountId;
        this.superAdmin = superAdmin;
        this.allAccess = allAccess;
        this.categoryIds = categoryIds == null
                ? Collections.emptySet()
                : Collections.unmodifiableSet(new LinkedHashSet<>(categoryIds));
    }

    public String getResourceType() {
        return resourceType;
    }

    public BigInteger getAccountId() {
        return accountId;
    }

    public Long getAccountIdAsLong() {
        return accountId == null ? null : accountId.longValue();
    }

    public boolean isSuperAdmin() {
        return superAdmin;
    }

    public boolean isAllAccess() {
        return allAccess;
    }

    public Set<BigInteger> getCategoryIds() {
        return categoryIds;
    }

    public boolean isRestricted() {
        return !superAdmin && !allAccess;
    }

    public boolean canAccess(BigInteger createdBy, BigInteger categoryId) {
        if (!isRestricted()) {
            return true;
        }
        if (accountId != null && accountId.equals(createdBy)) {
            return true;
        }
        return categoryId != null && categoryIds.contains(categoryId);
    }
}
