require 'history_client'

module Subscriptions
  class NotificationToken < Subscriptions::Base
    AUDIT_ACTION_GRANT_TOKEN = "grant_subscription_notification_token"
    AUDIT_TWITCH_USER = "twitch_user"
    AUDIT_LDAP_USER = "ldap_user"
    AUDIT_CHANGE_TOKEN_CHANNEL = "token_in_channel"
    AUDIT_DEFAULT_EXPIRY = 2 * 60 * 60 * 24 * 365 # 2 years

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

      change = History::ChangeSet.new(
        attribute: AUDIT_CHANGE_TOKEN_CHANNEL,
        new_value: options[:channel_id]
      )

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

      client.add(audit)
    end

    def self.grant_token(params)
      options = {
        user_id: params[:user_id],
        kind: params[:kind],
        tenure: params[:tenure],
        available_at: params[:available_at]
      }
      response = post "/internal/channels/#{params[:channel_id]}/notification_token", body: options.to_json
      if response.success?
        audit_token_grant(params)
      end

      response
    end
  end
end
