
// sequelize.<%- js %> - Sequelize adapter for SQL server.
<%- tplTsOnly([`import { App } from './app.interface'${sc}`, '']) -%>
<%- tplImports('url', null, 'req') %>
<%- tplImports('Sequelize', 'sequelize', 'req') %>
let { Op } = Sequelize<%- sc %>
<%- insertFragment('imports') %>
<%- insertFragment('init') %>

const operatorsAliases = {
  $eq: Op.eq,
  $ne: Op.ne,
  $gte: Op.gte,
  $gt: Op.gt,
  $lte: Op.lte,
  $lt: Op.lt,
  $not: Op.not,
  $in: Op.in,
  $notIn: Op.notIn,
  $is: Op.is,
  $like: Op.like,
  $notLike: Op.notLike,
  $iLike: Op.iLike,
  $notILike: Op.notILike,
  $regexp: Op.regexp,
  $notRegexp: Op.notRegexp,
  $iRegexp: Op.iRegexp,
  $notIRegexp: Op.notIRegexp,
  $between: Op.between,
  $notBetween: Op.notBetween,
  $overlap: Op.overlap,
  $contains: Op.contains,
  $contained: Op.contained,
  $adjacent: Op.adjacent,
  $strictLeft: Op.strictLeft,
  $strictRight: Op.strictRight,
  $noExtendRight: Op.noExtendRight,
  $noExtendLeft: Op.noExtendLeft,
  $and: Op.and,
  $or: Op.or,
  $any: Op.any,
  $all: Op.all,
  $values: Op.values,
  $col: Op.col
}<%- sc %>

<%- tplExport('function (app) {', 'function (app: App) {') %>
  let connectionString = app.get('mssql')<%- sc %>
  let connection = url.parse(connectionString)<%- sc %>
  let database = connection.path<%- tplTsOnly(['!']) %>.substring(1, connection.path<%- tplTsOnly(['!']) %>.length)<%- sc %>
  let { port, hostname } = connection<%- sc %>
  let [ username, password ] = (connection.auth || ':').split(':')<%- sc %>
  let sequelize = new Sequelize(database, username, password, {
    dialect: 'mssql',
    host: hostname,
    logging: false,
    operatorsAliases,
    define: {
      freezeTableName: true
    },
    dialectOptions: {
      port,
      instanceName: 'NameOfTheMSSQLInstance'
    }
  })<%- sc %>

  let oldSetup = app.setup<%- sc %>
  <%- insertFragment('func_init') %>

  app.set('sequelizeClient', sequelize)<%- sc %>

  app.setup = function (...args<%- tplTsOnly(': any[]') -%>) {
    let result = oldSetup.call(this, ...args)<%- sc %>
    <%- insertFragment('func_init') %>

    // Set up data relationships
    let models = sequelize.models<%- sc %>
    Object.keys(models).forEach(name => {
      if ('associate' in models[name]) {
        models[name].associate<%- tplTsOnly('!') -%>(models)<%- sc %>
      }
    })<%- sc %>

    // Sync to the database
    sequelize.sync()<%- sc %>

    <%- insertFragment('func_return') %>
    return result<%- sc %>
  }<%- sc %>
  <%- insertFragment('more') %>
}<%- tplJsOnly([sc]) %>
<%- insertFragment('funcs') %>
<%- insertFragment('end') %>
