import _ from 'lodash';
import {foreignKeyRelationshipName} from './foreign_key_name';

export const READ = 'READ';
export const WRITE = 'WRITE';

const buildInclude = (mode, model, db, models, exclude) => {
  const include = db.relationships.map(rel => {
    if (_.find(exclude, e => e === rel.model || e === rel.references)) {
      return null;
    }

    if (mode === READ && !rel.includeInSelect) {
      return null;
    }

    if (mode === WRITE && !rel.includeInWrite) {
      return null;
    }

    if (rel.model === model.name) {
      const related = models[rel.references];
      return {
        as: foreignKeyRelationshipName(rel),
        model: related,
        include: buildInclude(mode, related, db, models, [...exclude, model.name]),
      };
    }

    if (rel.references === model.name) {
      const related = models[rel.model];
      return {
        as: foreignKeyRelationshipName(rel),
        model: related,
        include: buildInclude(mode, related, db, models, [...exclude, model.name]),
      };
    }

    return null;
  });

  return _.filter(include, m => !_.isNil(m));
};

export const buildOptions = (mode, model, db, models) => {
  const include = buildInclude(mode, model, db, models, []);

  return {include};
};

@@ -17,16 +17,69 @@
 odash';%0A
+import %7BMANY_TO_ONE, MANY_TO_MANY%7D from 'node-bits';%0A
 import %7B
@@ -409,125 +409,207 @@
     
-if (mode === READ && !rel.includeInSelect) %7B%0A      return null;%0A    %7D%0A%0A    if (mode === WRITE && !rel.includeInWrite)
+let currentConfig = mode === WRITE%0A      ? rel.includeInWrite%0A      : rel.includeInSelect;%0A%0A    if (!currentConfig) %7B%0A      return null;%0A    %7D else if (currentConfig === true) %7B%0A      currentConfig =
  %7B%0A 
@@ -613,35 +613,94 @@
 %7B%0A      
+  
-return null
+model: true,%0A        reverse: true,%0A        separate: false,%0A      %7D
 ;%0A    %7D%0A
 %0A    if 
@@ -683,33 +683,32 @@
 %0A      %7D;%0A    %7D%0A
-%0A
     if (rel.mode
@@ -715,32 +715,55 @@
 l === model.name
+ && currentConfig.model
 ) %7B%0A      const 
@@ -956,32 +956,133 @@
 , model.name%5D),%0A
+        separate: currentConfig.separate && (rel.type === MANY_TO_MANY %7C%7C rel.type === MANY_TO_ONE),%0A
       %7D;%0A    %7D%0A%0A
@@ -1118,16 +1118,41 @@
 del.name
+ && currentConfig.reverse
 ) %7B%0A    
@@ -1352,24 +1352,125 @@
 del.name%5D),%0A
+        separate: currentConfig.separate && (rel.type === MANY_TO_MANY %7C%7C rel.type === MANY_TO_ONE),%0A
       %7D;%0A   

Support for additional includes config