import { Sequelize } from 'sequelize';
import LoggingService from '#services/file-system/logService';
import Config from '#config';

/** Threshold in ms — queries slower than this are logged as WARN */
const SLOW_QUERY_THRESHOLD_MS = Config.database.slowQueryThresholdMs;

const logger = new LoggingService();

const sequelize: Sequelize = new Sequelize({
	username: Config.database.user,
	password: Config.database.password,
	database: Config.database.name,
	host: Config.database.host,
	port: Config.database.port,
	dialect: 'postgres',
	// PERF-03: Optimized connection pool configuration for production
	pool: {
		max: Config.database.pool.max,
		min: Config.database.pool.min,
		acquire: Config.database.pool.acquire,
		idle: Config.database.pool.idle,
		evict: Config.database.pool.evict,
	},
	benchmark: true, // Pass execution time (ms) as second arg to `logging`
	logging(sql, timing) {
		const durationMs = typeof timing === 'number' ? timing : null;
		// Log all SQL to console in development
		// if (process.env.NODE_ENV === 'development') {
		// 	console.log(`[SQL] ${durationMs !== null ? `[${durationMs}ms] ` : ''}${sql}`);
		// }
		if (durationMs !== null && durationMs >= SLOW_QUERY_THRESHOLD_MS) {
			logger.logAsync('slow_query', 'Sequelize', `[${durationMs}ms] ${sql}`, null);
		} else {
			logger.logDBAsync(sql);
		}
	},
});

export default sequelize;
