using RpgRoller.Domain;

namespace RpgRoller.Services;

public static class GameAuthorization
{
    public static bool HasRole(UserAccount user, string role)
    {
        return RoleSerializer.HasRole(user.Roles, role);
    }

    public static bool CanViewCampaign(GameStateStore stateStore, Guid actorUserId, Guid campaignId)
    {
        if (stateStore.UsersById.TryGetValue(actorUserId, out var user) && HasRole(user, UserRoles.Admin))
            return true;

        var campaign = stateStore.CampaignsById[campaignId];
        if (campaign.GmUserId == actorUserId)
            return true;

        return stateStore.CharactersById.Values.Any(character => character.CampaignId == campaignId && character.OwnerUserId == actorUserId);
    }

    public static bool CanEditCharacter(Guid actorUserId, Character character, Campaign campaign)
    {
        return character.OwnerUserId == actorUserId || campaign.GmUserId == actorUserId;
    }

    public static bool CanViewRoll(GameStateStore stateStore, Guid actorUserId, Campaign campaign, RollLogEntry entry)
    {
        return CanViewCampaign(stateStore, actorUserId, campaign.Id) && (entry.Visibility == RollVisibility.Public || entry.RollerUserId == actorUserId || campaign.GmUserId == actorUserId);
    }
}