const { Model } = require('objection');
const Knex = require('knex');
const path = require('path');
const fs = require('fs');
require('dotenv').config();
const dbConfig = require(path.resolve(process.env.ROOT_PATH, './knexfile'))[process.env.NODE_ENV];
const knex = Knex(dbConfig);
const modelPath = path.resolve(process.env.ROOT_PATH, './db/models');

Model.knex(knex);

const db = {
  knex,
  Model,
  models: {}
};

fs.readdirSync(modelPath)
  .filter(file => file.endsWith('.js') && !file.startsWith('BaseModel'))
  .forEach(file => {
    const modelName = file.split('.')[0];
    const ModelClass = require(path.join(modelPath, file));
    db.models[modelName] = ModelClass;
  });

module.exports = db;