module Support
  module Services
    class OwsPayment
      include HTTParty

      base_uri DOMAINS[:ows_payment]

      class << self
        def generate_payment_group_body
          name = "orcd_autotest_#{Time.now.strftime('%s')}"
          { group_name: "group_name_#{name}",
            payment_name: "payment_name_#{name}",
            is_reusable: true,
            group_criteria: { currency_codes: ["CAD"],
                              payment_agreements: ["The Orchard", "Finetunes"],
                              payment_schedules: ["30 days after month end"] } }
        end

        def post_payment_group(body)
          path = "/payment-group"

          response = post(path, headers: { "Content-Type" => "application/json" }, body: body.to_json)

          verify_success(response, 201)
          response
        end

        def post_group_payment(body)
          path = "/payment-group-payment"

          response = post(path, headers: { "Content-Type" => "application/json" }, body: body.to_json)

          verify_success(response, 201)
          response
        end

        def post_group_payment_payees_bulk(payment_group_id, body)
          path = "/payment-group-payment/#{payment_group_id}/payees/"

          response = post(path, headers: { "Content-Type" => "application/json" }, body: body.to_json)

          verify_success(response, 201)
          response
        end

        def put_payment_group_payment(payment_group_payment_id, body)
          path = "/payment-group-payment/#{payment_group_payment_id}"

          response = put(path, headers: { "Content-Type" => "application/json" }, body: body.to_json)

          verify_success(response, 200)
          response
        end

        def generate_payment_group_payment(payment_group_body)
          response_post_payment_group = Support::Services::OwsPayment.post_payment_group(payment_group_body)
          JSON.parse(response_post_payment_group.body)["payment_group_payment_id"]
        end

        private

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