import {error, HELP_IDS} from '../createValidationResult'
import {flatten, isObject} from 'lodash'
import {getDupes} from '../utils/getDupes'

function normalizeToProp(typeDef) {
  if (Array.isArray(typeDef.to)) {
    return typeDef.to
  }
  return typeDef.to ? [typeDef.to] : typeDef.to
}
export default (typeDef, visitorContext) => {

  const to = normalizeToProp(typeDef)
  const toIsArray = Array.isArray(to)

  const problems = flatten([
    toIsArray
      ? getDupes(to, t => `${t.name};${t.type}`).map(dupes =>
        error(
          `Found ${dupes.length} members with same type, but not unique names "${dupes[0]
            .type}" in reference. This makes it impossible to tell their values apart and you should consider naming them`,
          HELP_IDS.REFERENCE_TO_INVALID
        ))
      : error(
        'The reference type is missing or having an invalid value for the required "to" property',
        HELP_IDS.REFERENCE_TO_INVALID
      )
  ])

  return {
    ...typeDef,
    to: to.map(visitorContext.visit),
    _problems: problems
  }
}

@@ -70,16 +70,21 @@
 tten, is
+Plain
 Object%7D 
@@ -288,16 +288,17 @@
 ef.to%0A%7D%0A
+%0A
 export d
@@ -348,36 +348,70 @@
 nst 
-to = normalizeToProp
+isValidTo = Array.isArray(typeDef.to) %7C%7C isPlainObject
 (typeDef
 )%0A  
@@ -406,16 +406,19 @@
 (typeDef
+.to
 )%0A  cons
@@ -423,36 +423,46 @@
 nst 
-toIsArray = Array.isArray(to
+normalizedTo = normalizeToProp(typeDef
 )%0A%0A 
@@ -497,17 +497,17 @@
     
-toIsArray
+isValidTo
 %0A   
@@ -520,17 +520,27 @@
 etDupes(
-t
+normalizedT
 o, t =%3E 
@@ -966,16 +966,58 @@
 property
+. It should be an array of accepted types.
 ',%0A     
@@ -1063,16 +1063,239 @@
 )%0A  %5D)%0A%0A
+  if (isValidTo && normalizedTo.length === 0) %7B%0A    problems.push(error(%0A      'The reference type should define at least one accepted type. Please check the %22to%22 property.',%0A      HELP_IDS.REFERENCE_TO_INVALID%0A    ))%0A  %7D%0A%0A
   return
@@ -1321,18 +1321,47 @@
     to: 
-to
+(isValidTo ? normalizedTo : %5B%5D)
 .map(vis

Improve reference type validation (#316)