const mysql = require("mysql2/promise");
const { Sequelize } = require("sequelize");

export const sequelize = new Sequelize(
    process.env.MYSQL_DATABASE,
    process.env.MYSQL_USERNAME,
    process.env.MYSQL_PASSWORD,
    {
        host: process.env.MYSQL_HOST,
        port: process.env.MYSQL_PORT || 3306,
        dialect: "mysql",
        logging: false,
    },
);

export default async () => {
    try {
        const connection = await mysql.createConnection({
            host: process.env.MYSQL_HOST,
            user: process.env.MYSQL_USERNAME,
            password: process.env.MYSQL_PASSWORD,
        });
        await connection.query(
            `CREATE DATABASE IF NOT EXISTS ${process.env.MYSQL_DATABASE}`,
        );
        await connection.end();
        await sequelize.authenticate();
        await sequelize.sync({ alter: true });
    } catch (err) {
        console.log(`[sequelize] ${err.message}`);
    }
};
