module DataHelpers
  class PhysicalProductMetadata
    attr_reader :data

    def initialize(account_type:, account_id:)
      @date = Date.today
      @stamp = new_timestamp
      @data = base_data.merge(account_data(account_type, account_id))
    end

    def add_configuration_mapping_fields
      @data.delete(:configuration)
      @data.merge!(
        configuration_product_type: "CD"
      )
    end

    def copy_to_digital_fields
      { product_name: @data[:product_name],
        format: @data[:format],
        product_version: @data[:product_version],
        version_notes: @data[:version_notes],
        genre: @data[:genre],
        subgenre: @data[:subgenre],
        imprint: @data[:imprint] }
    end

    def replace_copy_fields
      new_stamp = new_timestamp
      @data.merge!(
        product_code: new_stamp,
        configuration_product_type: "CD",
        format: "EP",
        units_per_set: 3,
        packaging: "Box Set",
        initial_stock: 7711,
        box_lot: 30,
        discount_policy: "-"
      )
      # upc doesn't get copied over
      @data.delete(:upc)
    end

    def replace_pre_existing_fields
      add_configuration_mapping_fields
      @data.merge!(yml_file[:physical_metadata][:pre_existing_release_data])
    end

    def fields
      @data.keys
    end

    private

    def base_data
      # must be at least 75 days in the future for physical products
      release_date = (@date + 80).to_s
      {
        product_name: "Watir Physical Product #{@stamp}",
        product_code: @stamp,
        upc: Support::Helpers::UPC.generate_unused_upc,
        release_date: release_date,
        sales_date: release_date
      }.merge!(yml_file[:physical_metadata][:all_data])
    end

    def account_data(type, id)
      physical_metadata = yml_file[:physical_metadata]
      data_for_account_type = physical_metadata[:account_dependent_fields][type]
      if data_for_account_type.nil?
        fail "no data for accounts of type '#{type}'!"
      end
      data_for_account = data_for_account_type[id]
      fail "no data for '#{type} #{id}'!" if data_for_account.nil?
      data_for_account
    end

    def yml_file
      YAML.load_file(
        File.join(Support::Paths.cucumber_root, "features", "yml", "physical_product_metadata.yml")
      ).deep_symbolize_keys
    end

    def new_timestamp
      Time.stamp.slice(0..11)
    end
  end
end
