module Substwirp
  class Subscription < Substwirp::Base

    self.primary_attribute = :id

    attributes :id,
      :product_id,
      :owner_id,
      :benefit_start,
      :benefit_end,
      :origin_id,
      :channel_id,
      :is_renewable

    def owner
      @owner ||= Twitch::User.find(owner_id)
    end

    def access_start
      @benefit_start
    end

    def access_end
      @benefit_end
    end

    def ticket_product_id
      @product_id
    end

    def self.get_by_purchase_profile(purchase_profile_id)
      response = twirp_client.get_tickets_by_origin_i_ds(
        origin_ids: [purchase_profile_id.to_s]
      )

      if !response.error && !response.data.subscriptions.empty?
        return from_twirp_object(response.data.subscriptions[-1])
      end
      Rails.logger.warn("received error or found no ticket for #{purchase_profile_id}")
      return nil
    end
  end
end