module Bits
  class Type < Service::Base
    include Code::Justin::Tv::Commerce::Petozi

    self.service_endpoint = Settings.petozi.endpoint
    self.primary_attribute = :id

    attributes :id, :display_name, :is_paid, :is_promotional, :cost_per_bits_usc, :entitlement_source_type, :spend_order, :business_attribution

    validates :id, :display_name, :is_paid, :is_promotional, :cost_per_bits_usc, :entitlement_source_type, :spend_order, :business_attribution, presence: true

    def self.twirp_client
      @twirp_client ||= PetoziClient.new(connection)
    end

    def self.all(_options = {})
      resp = twirp_client.get_bits_types(GetBitsTypesReq.new)

      raise resp.error.msg if resp.error

      resp.data.bits_types.map { |t| self.from_twirp_object(t) }.sort_by(&:id)
    end

    def self.find(id)
      resp = twirp_client.get_bits_type(GetBitsTypeReq.new(id: id))

      raise resp.error.msg if resp.error

      return self.from_twirp_object(resp.data.bits_type)
    end

    def self.entitlement_source_types
      EntitlementSourceType.constants.sort_by { |c| EntitlementSourceType.resolve(c) }
    end

    def self.business_attributions
      BusinessAttribution.constants.sort_by { |c| BusinessAttribution.resolve(c) }
    end

    def save
      req = PutBitsTypeReq.new(
        bits_type: BitsType.new(
          id: @id,
          display_name: @display_name,
          is_paid: @is_paid,
          is_promotional: @is_promotional,
          cost_per_bits_usc: @cost_per_bits_usc,
          entitlement_source_type: @entitlement_source_type,
          business_attribution: @business_attribution
        )
      )

      resp = self.class.twirp_client.put_bits_type(req)
      self.errors = resp.error.msg if resp.error

      return !resp.error
    end

  end
end
