#
# HasOffers Affiliate API
# https://developers.tune.com/affiliate/affiliate_report-getconversions/

module Payback
  module Networks
    class Digitaladvisor < Base

      required_credentials :api_key

      URL = 'https://digitaladvisor.api.hasoffers.com/Apiv3/json'
      STATUS_MAPPINGS = {
        'pending' => Conversion::PENDING,
        'approved' => Conversion::APPROVED,
        'rejected' => Conversion::REJECTED
      }
      RESPONSE_TIMEZONE = 'Europe/Copenhagen'
      NETWORK_ID = 'digitaladvisor'
      FIELDS = [
        "Stat.refer", # referrer
        "Stat.currency",
        "Offer.name",  # program
        "Stat.offer_id", # program_id
        "Stat.id", # ID of the unique object for the conversion
        "Stat.sale_amount", # order_value
        "Stat.conversion_status",
        "Stat.datetime", # Time of sale
        "Stat.approved_payout", # commission
        "Stat.affiliate_info1", # EPI
        "Stat.session_datetime", # clicked_at
      ]

      def fetch(from, to)

        res = Excon.get(URL,
          query: {
            'api_key' => api_key,
            'Target' => 'Affiliate_Report',
            'Method' => 'getConversions',
            'fields[]' => FIELDS,
            'data_start' => from.strftime('%Y-%m-%d'),
            'data_end' => to.strftime('%Y-%m-%d'),
            'filters[Stat.datetime][conditional]' => 'BETWEEN',
            'filters[Stat.datetime][values][]' => [from.strftime('%Y-%m-%d'), to.strftime('%Y-%m-%d')]
          },
          expects: [200]
        )

        data = Payback.parse_json(res.body)

        if error_msg = data['response']['errorMessage']
          raise(Payback::RequestError.new, error_msg)
        else
          parse(data['response']['data']['data'])
        end

      end

      def parse(data)
        data.map do |entry|
          Conversion.new(
            program: entry['Offer']['name'],
            program_id: entry['Stat']['offer_id'],
            currency: entry['Stat']['currency'],
            uid: entry['Stat']['id'],
            network: 'digitaladvisor',
            epi: entry['Stat']['affiliate_info1'],
            channel: nil,
            commission: entry['Stat']['approved_payout'],
            timestamp: local_time_to_utc(entry['Stat']['datetime']),
            clicked_at: local_time_to_utc(entry['Stat']['session_datetime']),
            status: parse_status(entry['Stat']['conversion_status']),
            order_value: entry['Stat']['sale_amount'],
            referrer: entry['Stat']['refer']
          )
        end
      end

    end
  end
end
