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

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

const User = sequelize.define(
  'User',
  {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, unique: true },
    firstName: { type: DataTypes.STRING, allowNull: false },
    lastName: { type: DataTypes.STRING, allowNull: false },
  },
  { timestamps: false },
);

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

    // create table
    await sequelize.sync();

    let users = await User.findAll({ attributes: ['firstName'] });
    User.destroy({ truncate: true, cascade: true, force: true });

    const user = await User.create({ firstName: 'John', lastName: 'Doe' });
    users = await User.findAll();

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