module Ads
  class RevenueConfig < Ads::Base
    self.service_endpoint = Settings.ads.rev_config_endpoint
    attributes :id, :user_id, :start_date, :end_date, :flat_rate_cpm_in_cents, :rev_split_percent,
                :t1_flat_rate_cpm_in_cents, :t1_rev_split_percent, :t2_flat_rate_cpm_in_cents,
                :t2_rev_split_percent, :created_at, :updated_at
    self.primary_attribute = :user_id

    def initialize(params = {})
      super(params)
      @start_date = Time.parse(@start_date) unless @start_date.nil? or @start_date.empty?
    end

    def save
      response = post '/', {
        body: create_params.to_json,
        headers: { 'content-type' => 'application/json' }
      }

      self.errors.add(:base, response.body['error_message']) unless response.success?
      response.success?
    end

    def destroy
      response = post "/#{@id}/"
      errors.add(:base, response.body) unless response.success?
      return response.success?
    end

    def create_params
      p = self.attributes
      p[:user_ids] = Array p.delete(:user_id)
      p[:start_date] = p.delete(:start_date).strftime("%Y-%m-%d")
      p.transform_values { |val| val == '' ? nil : val }
    end

    def self.find(user_id)
      today = DateTime.now.next_year.strftime("%Y-%m-%d")
      configs = []
      response = get "/#{user_id}/1970-01-01/#{today}/"
      return from_errors(response.body) unless response.success?

      response.body['result'].sort_by { |h| h['start_date'] }.reverse.each do |row|
        configs <<= RevenueConfig.new row['config']
      end
      return configs
    end
  end
end
