class UPC
  def self.validate(row, repo)
    reasons = []

    if row[:upc] && invalid_length?(row[:upc])
      reasons << 'UPC must be 12 or 13 characters long'
    end

    if row[:upc] && !row[:distribution_type]
      reasons << 'UPC must be blank if distribution type is blank'
    end

    if row[:upc] && !valid_contract?(row[:upc], row[:contract_id], repo)
      reasons << 'UPC is not on this contract'
    end

    reasons
  end

  def self.valid_contract?(upc, contract_id, repo)
    upc = upc.to_s.gsub('.0', '')

    if repo.check_contract_has_upc_attached(contract_id, upc)
      return true
    elsif repo.check_contract_has_upc_attached_ignore_leading_zero(contract_id, upc)
      return true
    elsif repo.check_contract_has_upc_attached_ignore_all_leading_zeros(contract_id, upc)
      return true
    elsif repo.check_upc_display_upc_mapping(contract_id, upc)
      return true
    elsif repo.contract_label_owns_upc?(contract_id, upc)
      return true
    else
      return false
    end
  end

  def self.invalid_length?(upc)
    upc = upc.to_s.gsub('.0', '')

    return true if upc.to_s.length < 12 || upc.to_s.length > 13
    false
  end
end
