require 'openssl'
require 'base64'

module Keys
  class Pool < Keys::Base

    attributes :pool_id, :product_type, :sku, :redemption_mode, :description, :handler_group_id, :handler, :start_date, :end_date, :ldap_login

    # TODO: Refactor to use twirp generated client once custom headers are supported
    def self.all(cursor, ldap_login)
      post(
        '/twirp/code.justin.tv.commerce.phanto.Phanto/GetAllKeyPools',
        body: { :cursor => cursor }.to_json,
        headers: Keys.ldap_header(ldap_login)
      )
    end

    def create
      post(
        '/twirp/code.justin.tv.commerce.phanto.Phanto/CreateKeyPool',
        body: {
            :pool_id => self.pool_id,
            :product_type => self.product_type,
            :sku => self.sku,
            :description => self.description,
            :handler_group_id => self.handler_group_id,
            :redemption_mode => self.redemption_mode,
            :start_date => self.start_date.to_datetime.rfc3339,
            :end_date => self.end_date.to_datetime.rfc3339
        }.to_json,
        headers: Keys.ldap_header(ldap_login)
      )
    end

    def invalidate
      post(
        '/twirp/code.justin.tv.commerce.phanto.Phanto/InvalidateKeyPool',
        body: {
            :pool_id => self.pool_id,
        }.to_json,
        headers: Keys.ldap_header(ldap_login)
      )
    end

    def update_status(new_status)
      post(
        '/twirp/code.justin.tv.commerce.phanto.Phanto/UpdateKeyPool',
        body: {
            :pool_id => self.pool_id,
            :status => new_status
        }.to_json,
        headers: Keys.ldap_header(ldap_login)
      )
    end

  end
end
