const { generateId } = require('../util')
const Sequelize = require('sequelize')
const {
  host,
  user,
  password,
  database,
  port,
  connectionLimit
} = require('../conf/config.inc').dbInfo.Web

console.log('init sequelize...')

const sequelize = new Sequelize(database, user, password, {
  host: host,
  port: port,
  dialect: 'mysql',
  pool: {
    max: connectionLimit,
    min: 0,
    idle: 10000
  }
})
/**
 * 连接测试
 */
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.')
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err)
  })

/**
 * 定义model
 */
module.exports.defineModel = function (name, attributes) {
  let attrs = {}
  attrs.id = {
    type: Sequelize.STRING(50),
    primaryKey: true
  }
  attrs.createdAt = {
    type: Sequelize.BIGINT,
    allowNull: false
  }
  attrs.updatedAt = {
    type: Sequelize.BIGINT,
    allowNull: false
  }
  attrs.version = {
    type: Sequelize.BIGINT,
    allowNull: false
  }
  for (let key in attributes) {
    let value = attributes[key]
    if (typeof value === 'object' && value['type']) {
      value.allowNull = value.allowNull || false
      attrs[key] = value
    } else {
      attrs[key] = {
        type: value,
        allowNull: false
      }
    }
  }
  return sequelize.define(name, attrs, {
    tableName: name,
    timestamps: false,
    hooks: {
      beforeValidate: function (obj) {
        let now = Date.now()
        if (obj.isNewRecord) {
          if (!obj.id) {
            obj.id = generateId()
          }
          obj.createdAt = now
          obj.updatedAt = now
          obj.version = 0
        } else {
          obj.updatedAt = Date.now()
          obj.version++
        }
      }
    }
  })
}

module.exports.sync = function () {
  // only allow create ddl in non-production environment:
  if (process.env.NODE_ENV !== 'production') {
    sequelize.sync({ force: true })
  } else {
    throw new Error("Cannot sync() when NODE_ENV is set to 'production'.")
  }
}
