module BeefCake
  class AttachedPermission < BeefCake::Base
    attributes :id, :role, :permission, :scope

    def self.all_channel_payout_scopes
      [
        Twitch::Fulton::Beefcake::PermissionScope.new(
          channel_payout: Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::NO_PAYOUT_TYPE
        ),
        Twitch::Fulton::Beefcake::PermissionScope.new(
          channel_payout: Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::AFFILIATE
        ),
        Twitch::Fulton::Beefcake::PermissionScope.new(
          channel_payout: Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::PARTNER
        ),
        Twitch::Fulton::Beefcake::PermissionScope.new(
          channel_payout: Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::DEVELOPER
        )
      ]
    end

    def self.find(role_id:, attached_permission_id:)
      Role
        .find(role_id)
        .attached_permissions
        .select { |p| p.id == attached_permission_id }
        .first
    end

    def delete
      handle_error(
        client.remove_legacy_permission_from_role(
          Twitch::Fulton::Beefcake::RemoveLegacyPermissionFromRoleRequest.new(
            role_id: role.id,
            legacy_permission_id: permission.id
          )
        )
      )
      true
    end

    def update_scope(new_scope)
      handle_error(
        client.update_role_permission_scope(
          Twitch::Fulton::Beefcake::UpdateRolePermissionScopeRequest.new(
            role_id: role.id,
            role_permission_id: id,
            scope: new_scope.map do |x|
              Twitch::Fulton::Beefcake::PermissionScope.new(
                channel_payout: Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType.resolve(x.to_sym)
              )
            end
          )
        )
      )
      true
    end

    def payout_entity_scope
      scope
        .map do |s|
          s.channel_payout.to_s
        end
    end

    def permitted_on_twitch_user?(twitch_user)
      return true if scope.empty?
      scope_required = permission_scope_required(twitch_user)
      scope
        .any? { |x| x.channel_payout == scope_required }
    end

    protected

    def permission_scope_required(twitch_user)
      scope_required = Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::NO_PAYOUT_TYPE
      if twitch_user.partner_program?
        scope_required = Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::PARTNER
      elsif twitch_user.affiliate?
        scope_required = Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::AFFILIATE
      elsif twitch_user.developer?
        scope_required = Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType::DEVELOPER
      end

      Twitch::Fulton::Beefcake::PermissionScope::ChannelPayoutType.lookup(scope_required)
    end
  end
end
