"use strict";

const Sequelize = require('sequelize'),
  config = require('config');

function init() {
  const db = {
    sequelize: new Sequelize(config.get("db.groups")),
    Sequelize: Sequelize
  };

  return db.sequelize.authenticate().then(function () {
    const Group = db.sequelize.define('group', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      name: Sequelize.STRING,
      ownerId: Sequelize.INTEGER
    }, {
      timestamps: false,
      classMethods: {
        associate: function() {}
      }
    });

    const GroupUsers = db.sequelize.define('groupuser', {
      groupId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: Group,
          key: 'id'
        }
      },
      userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
      }
    }, {
      timestamps: false
    });

    return db.sequelize.sync({
      force: false
    }).then(function () {
      return db;
    });
  }).catch(function (error) {
    console.log("ERROR: Failed to authenticate with GROUP DB");
    console.log("ERROR: " + JSON.stringify(config.get("db"), null, 2));
    console.log(error);
    throw error;
  });
}

module.exports = init();
