module TwitchZuko
  class RedemptionsHistory < TwitchZuko::Base
    self.primary_attribute = :id
    attributes :id, :user_id, :redeem_amount, :currency, :serial_number, :redemption_status, :vendor, :redemption_time

    def self.call(param_user_id, param_serial_number, param_start_date, param_end_date)
      if param_start_date.present?
        start_date = time_to_protobuf_timestamp(param_start_date)
      end

      if param_end_date.present?
        end_date = time_to_protobuf_timestamp(param_end_date)
      end

      req = Twitch::Fulton::Twitchzuko::GetRedemptionHistoryRequest.new(
        user_id: param_user_id,
        serial_number: param_serial_number,
        created_on_start: start_date,
        created_on_end: end_date
      )
      resp = twirp_client.get_redemption_history(req)

      raise resp.error.msg if resp.error

      resp.data.redemption_history.map { |v| self.from_twirp_object(v) }
    end

    def self.time_to_protobuf_timestamp(time_str)
      parsed_time = Time.parse(time_str)

      Google::Protobuf::Timestamp.new(seconds: parsed_time.to_i)
    end
  end
end