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

const sequelize = new Sequelize('app_db', 'db_user', 'db_user_pass', {
  host: 'mysql',
  port: 3306,
  dialect: 'mysql',
});

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 },
  },
  { 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 sequelize.sync();

    await Auth.destroy({ truncate: true, cascade: true, force: true });

    let user_row, password;
    user_row = await Auth.create({ username: 'admin@vtkhmall.com', password: await hashPassword('nimda') });
    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);
  }
})();
