import dotenv from 'dotenv';
import { Sequelize } from 'sequelize';

dotenv.config();

const sequelize = new Sequelize(
    process.env.DB_NAME || 'deytal',
    process.env.DB_USER || 'root',
    process.env.DB_PASSWORD || '',
    {
        host: process.env.DB_HOST || 'localhost',
        dialect: 'mysql',
        logging: false,
        dialectOptions: {
            timezone: 'Z'
        },
        define: {
            underscored: true
        }
    }
);

export const testConnection = async () => {
    try {
        await sequelize.authenticate();
        try {
            await sequelize.sync({ alter: true });
        } catch (syncError) {
            if (syncError?.original?.code !== 'ER_TOO_MANY_KEYS') {
                throw syncError;
            }

            console.error('Sequelize alter-sync hit MySQL key limit. Continuing with normal sync.');
            await sequelize.sync();
        }
        console.log('Database connection established successfully. Schema synchronized.');
        return true;
    } catch (error) {
        console.error('Unable to connect to the database:', error);
        if (error && error.original && error.original.code === 'ER_TOO_MANY_KEYS') {
            console.error('Sequelize sync failed because the existing table already has too many indexes.');
            console.error('Fix: remove redundant indexes from the users table or avoid alter-sync on this database.');
        }
        return false;
    }
};

export default sequelize;
