require 'history_client'

module Badges
  class Subscriptions < Badges::Base
    AUDIT_ACTION_OVERRIDE = "override_sub_badge"
    AUDIT_ACTION_REVOKE = "revoke_sub_badge"
    AUDIT_TWITCH_USER = "twitch_user"
    AUDIT_LDAP_USER = "ldap_user"
    AUDIT_CHANGE_BADGE_VERSION = "badge_version"
    AUDIT_DEFAULT_EXPIRY = 2 * 60 * 60 * 24 * 365 # 2 years

    def self.audit_badge_override(options)
      client = History::Client.new(Settings.history)

      change = History::ChangeSet.new(
        attribute: AUDIT_CHANGE_BADGE_VERSION,
        new_value: options[:badge_set_version]
      )

      audit = History::Audit.new(
        action: options[:audit_action],
        user_type: AUDIT_LDAP_USER,
        user_id: options[:ldap_login],
        resource_type: AUDIT_TWITCH_USER,
        resource_id: options[:user_id].to_s,
        description: "In channel: #{options[:channel_id]}",
        changes: [change],
        created_at: Time.now.utc.round(3).iso8601(3),
        expiry: AUDIT_DEFAULT_EXPIRY
      )

      client.add(audit)
    end

    def self.entitle(params)
      options = {badge_set_version: params[:badge_set_version]}
      response = post "/v1/badges/users/#{params[:user_id]}/channels/#{params[:channel_id]}/subs", body: options.to_json
      if response.success?
        audit_options = params.merge(audit_action: AUDIT_ACTION_OVERRIDE)
        audit_badge_override(audit_options)
      end

      response
    end

    def self.revoke(params)
      response = delete "/v1/badges/users/#{params[:user_id]}/channels/#{params[:channel_id]}/subs"
      if response.success?
        audit_options = params.merge(audit_action: AUDIT_ACTION_REVOKE)
        audit_badge_override(audit_options)
      end

      response
    end

    def self.override(params)
      # Decide if we're entitling or revoking a badge
      if params[:badge_set_version] == "None"
        response = revoke(params)
      else
        response = entitle(params)
      end

      response
    end
  end
end
