module Substwirp
  class RevenueConfig < Substwirp::Base
    self.primary_attribute = :id

    attributes :id, :product_id, :start_date, :rev_split_percent, :created_at, :updated_at

    def self.get_configs_for_product_id(product_id)
      response = twirp_client.get_revenue_configs_by_product_i_d(
        product_id: product_id.to_s
      )
      raise response.error.msg if response.error

      response.data.revenue_configs.map { |v| self.from_twirp_object(v) }
    end

    def self.get_by_id(revenue_config_id)
      response = twirp_client.get_revenue_config(
        revenue_config_id: revenue_config_id.to_s
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data.revenue_config)
    end

    def self.update(revenue_config_id, start_date, rev_split_percent)
      response = twirp_client.update_revenue_config(
        revenue_config_id: revenue_config_id,
        start_date: time_to_protobuf_timestamp(start_date),
        rev_split_percent: rev_split_percent.to_i
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data.revenue_config)
    end

    def self.delete(revenue_config_id)
      response = twirp_client.delete_revenue_config(
        revenue_config_id: revenue_config_id
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data.revenue_config)
    end

    def self.create(product_id, start_date, rev_split_percent)
      response = twirp_client.create_revenue_config(
        product_id: product_id,
        start_date: time_to_protobuf_timestamp(start_date),
        rev_split_percent: rev_split_percent.to_i
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data.revenue_config)
    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
