module Support
  module Services
    class OwsProductDigital
      include HTTParty

      base_uri DOMAINS[:ows_product_digital]

      class << self
        def submit_product(product_id, session_id)
          path = "/product/audio/#{product_id}/status"
          headers = {
            "Content-Type" => "application/json",
            "session" => session_id
          }
          response = put(path, headers: headers)

          JSON.parse(response.body)
        end

        def create_correction(product_id, session_id)
          path = "/product/#{product_id}/correction"
          options = {
            body: {}.to_json,
            headers: {
              "Content-Type" => "application/json",
              "session" => session_id
            }
          }
          response = post(path, options)

          JSON.parse(response.body)
        end

        def create_correction_details(product_id, correction_id, session_id)
          path = "/product/#{product_id}/correction/#{correction_id}/details"
          options = {
            body: { "items": [{ "field_name": "release_name", "key_value": "Test #{Time.stamp}",
                                "key_id": product_id, "table_name": "releases" }] }.to_json,
            headers: {
              "Content-Type" => "application/json",
              "session" => session_id
            }
          }
          response = post(path, options)

          JSON.parse(response.body)
        end

        def add_subgenre_and_artist(product_id, product_data, session_id)
          path = "/product/audio/#{product_id}"
          payload = { "subgenre_id": product_data["subgenre_id"],
                      "product_artists": product_data["product_artists"] }
          options = {
            body: payload.to_json,
            headers: {
              "Content-Type" => "application/json",
              "session" => session_id
            }
          }
          response = put(path, options)
          return if response.code == 200
          fail("Error updating product via ows-product, error code #{response.code}")
        end

        def create_product(project_id, session_id, label)
          path = "/product/audio"

          product_data = JSON.parse(File.read("features/json/digital_product_data.json"))[label]
          product_data["project_id"] = project_id

          options = {
            body: product_data.to_json,
            headers: { "Content-Type" => "application/json", "session" => session_id }
          }
          response = post(path, options)
          fail("Error creating product via ows-product, error code #{response.code}") unless
              response.code == 201
          add_subgenre_and_artist(response["product_id"], product_data, session_id) if
              product_data.key?("subgenre_id")

          JSON.parse(response.body)
        end
      end
    end
  end
end
