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();

/**
 * Dedicated DB connection pool for worker services
 *
 * Separate pool to avoid contention with main API service
 * Smaller pool size (5 connections) optimized for background processing
 */
const workerSequelize: 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',
	// Worker-specific pool configuration (smaller than main API)
	pool: {
		max: 5, // Worker needs fewer connections than API
		min: 1, // Keep at least 1 connection alive
		acquire: 30000, // 30 seconds to acquire connection
		idle: 10000, // 10 seconds idle timeout
		evict: 60000, // Evict connections after 60 seconds
	},
	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', 'WorkerSequelize', `[${durationMs}ms] ${sql}`, null);
		} else {
			logger.logDBAsync(sql);
		}
	},
});

export default workerSequelize;
