module Support
  module Services
    class OwsAccounting
      include HTTParty

      base_uri DOMAINS[:ows_accounting]

      class << self
        def get_report_url(headers, query)
          path = "/report-link"

          response = get(path, headers: headers, query: query)

          verify_success(response)
          response
        end

        def report_type_matcher(report_type)
          case report_type
          when "full"
            "all"
          else
            report_type
          end
        end

        def number_format_matcher(number_format)
          case number_format
          when "US"
            "en_US"
          when "EU"
            "es_ES"
          end
        end

        def periods_from_url(browser_url)
          periods = browser_url.match(".*\/period.*\/(.*)\/(.*)\/").captures
          if periods[0] == periods[1]
            periods.first
          else
            (periods[0]..periods[1]).to_a.join(",")
          end
        end

        def generate_headers(user)
          account_type = if user.name.to_s.include?("subaccount")
                           "subaccount"
                         else
                           "vendor"
                         end

          { "Content-Type" => "application/json",
            "Orchard-User-Id" => "alw:#{user.info[:vend_contact_id]}",
            "Grass-Account-Type" => account_type,
            "Grass-Account-Id" => user.info[:id].to_s }
        end

        def generate_query_get_report_url(file_type:, number_format:, report_format:, periods:)
          { "file_type" => file_type,
            "number_format" => number_format,
            "transaction_types" => report_format,
            "periods" => periods }
        end

        private

        def verify_success(response)
          return if response.code == 200
          fail(
            "request to ows-accounting did not succeed:"\
              " #{JSON.parse(response.body)}"
          )
        end
      end
    end
  end
end
