module Support
  module Services
    class OwsRoyalties
      include HTTParty

      base_uri DOMAINS[:ows_royalties]

      class << self
        def retrieve_recent_statement_periods
          path = "/statement-periods/recent/"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def retrieve_accounting_periods
          path = "/accounting-periods"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def retrieve_sales_files(period_id)
          path = "/accounting-period/#{period_id}/sales-files"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def retrieve_accounting_period(period_id)
          path = "/accounting-period/#{period_id}"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def retrieve_accounting_runs(period_id)
          path = "/accounting-period/#{period_id}/accounting-runs"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def put_sales_file(sales_file_id, body)
          path = "/sales-file/#{sales_file_id}"

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

          verify_success(response)
          response
        end

        def put_accounting_run(acc_run_id, status)
          path = "/accounting-run/#{acc_run_id}"
          body = { "accounting_run_status" => status }

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

          verify_success(response)
          response
        end

        def get_run_summary_download_url(accounting_run_id)
          path = "/accounting-run/#{accounting_run_id}/summary/download"

          response = get(path, headers: { "Content-Type" => "application/json" })

          verify_success(response)
          response
        end

        def update_accounting_period_status(period_id, status)
          body = { "accounting_period_status" => status }

          path = "/accounting-period/#{period_id}"

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

          verify_success(response)
          response
        end

        private

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