#! /usr/bin/env node
declare var require;

import {bootstrap} from "./lib/bootstrap";
import { IConfig } from "./lib/interfaces/config";

const root = require('path').resolve(process.cwd());
const args = process.argv.slice(2);
let configFile = `${root}/config.json`;

if (args && args.length) {
    configFile = `${root}/${args[0]}`;
}
const config = require('fs-extra').readJsonSync(configFile);


if (!config.ENV && !config.DATABASE_CONNECTION_SETTINGS[config.ENV]) {
    throw new Error(`Set ENV and DATABASE_CONNECTION_SETTINGS[ENV]`);
}

if (!config.CRUD_GENERATE) {
    throw new Error(`Missing CRUD_GENERATE property`);
}

//bootstrap(mergeConfig({...config, root}));

// TODO get rid of output
const lookup = config.ORM_GENERATE.lookup && typeof config.ORM_GENERATE.lookup === "object" ? config.ORM_GENERATE.lookup : {tableName: null, identifier: null};
const crudGenerate = config.CRUD_GENERATE && typeof config.CRUD_GENERATE === "object" ? config.CRUD_GENERATE : {shouldGenerate: false};
const ormGeneratePath = {
    
    // ORM
    daos: config.ORM_GENERATE.path && config.ORM_GENERATE.path.daos ? `${root}/${config.ORM_GENERATE.path.daos}` : `${root}/src/daos`,
    services: config.ORM_GENERATE.path && config.ORM_GENERATE.path.services ? `${root}/${config.ORM_GENERATE.path.services}` : `${root}/src/services`,
    interface: config.ORM_GENERATE.path && config.ORM_GENERATE.path.interface ? `${root}/${config.ORM_GENERATE.path.interface}` : `${root}/src/interfaces/interfaces.generated.ts`,
    ormWrapper: config.ORM_GENERATE.path && config.ORM_GENERATE.path.ormWrapper ? `${root}/${config.ORM_GENERATE.path.ormWrapper}` : `${root}/src/classes/Orm.ts`,
    
    // CRUD
    controllers: `${root}/src/controllers`,
    sequelizeConfig: `${root}/src/datasources/sequelize.ts`,
    env: `${root}/.env`,
    packageJSON: `${root}/package.json`
};
const mergedConfig: IConfig = {
    ...{
        ENV: config.ENV,
        DATABASE_CONNECTION_SETINGS: {
            [config.ENV]: {
                ...config.DATABASE_CONNECTION_SETINGS[config.ENV]
            }
        },
        ORM_GENERATE: {
            shouldGenerateServices: config.ORM_GENERATE.shouldGenerateServices || false, // todo: will need more logic to account for Controller generation
            caseSensitiveProps: config.ORM_GENERATE.caseSensitiveProps || [],
            skipTables: config.ORM_GENERATE.caseSensitiveProps || [],
            manyToManyIdentifiers: config.ORM_GENERATE.manyToManyIdentifiers || ["map"],
            lookup,
            pkIdentifier: config.ORM_GENERATE.pkIdentifier || "id",
            path: ormGeneratePath
        },
        CRUD_GENERATE: crudGenerate
    },
    root
}

bootstrap(mergedConfig);
