const { Sequelize, DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const { sequelize } = require('./model');

function delay(time_ms) {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res();
    }, time_ms);
  });
}

const Auth = sequelize.define(
  'Auths',
  {
    uid: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, unique: true },
    username: { type: DataTypes.STRING, allowNull: false },
    password: { type: DataTypes.STRING, allowNull: false },
    session: { type: DataTypes.STRING, allowNull: false, defaultValue: '' },
    role: { type: DataTypes.STRING, allowNull: false, defaultValue: 'customer' },
  },
  { timestamps: false },
);

async function hashPassword(plainTextPassword) {
  const saltRounds = 10;
  return await bcrypt.hash(plainTextPassword, saltRounds);
}

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');

    // create table
    await Auth.drop();
    await sequelize.sync();

    let user_row, password;
    user_row = await Auth.create({
      username: 'admin@vtkhmall.com',
      password: await hashPassword('nimda'),
      role: 'admin',
    });
    user_row = await Auth.create({ username: 'cust1@vtkhmall.com', password: await hashPassword('1tsuc') });
    user_row = await Auth.create({ username: 'cust2@vtkhmall.com', password: await hashPassword('2tsuc') });
    user_row = await Auth.create({ username: 'cust3@vtkhmall.com', password: await hashPassword('3tsuc') });

    // await sequelize.close();
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();
