import { OutboxPoller } from '../jobs/outboxPoller';
import Logger from '#utils/logger';
import workerSequelize from '#services/database/sequelize/workerSequelizeService';
// Config import commented out due to hang issue - worker doesn't use Config currently

/**
 * Audit Worker Service
 *
 * Separate worker process for processing audit events
 * Runs independently from the main API service
 * Uses dedicated DB connection pool to avoid contention
 * No HTTP server - runs as background process
 */
class AuditWorker {
	private static isShuttingDown = false;

	static async start() {
		Logger.info('Starting Audit Worker Service...');

		// Initialize database connection
		try {
			Logger.info('Audit Worker: Connecting to database...');
			await workerSequelize.authenticate();
			Logger.info('Audit Worker: Database connection established');
		} catch (error) {
			Logger.error('Audit Worker: Failed to connect to database', error);
			process.exit(1);
		}

		// Start OutboxPoller
		try {
			Logger.info('Audit Worker: Starting OutboxPoller...');
			OutboxPoller.start();
			Logger.info('Audit Worker: OutboxPoller started');
		} catch (error) {
			Logger.error('Audit Worker: Failed to start OutboxPoller', error);
			process.exit(1);
		}

		// Handle graceful shutdown
		Logger.info('Audit Worker: Setting up shutdown handlers...');
		this.setupShutdownHandlers();

		Logger.info('Audit Worker Service started successfully (running as background process)');
	}

	private static setupShutdownHandlers() {
		const shutdown = async (signal: string) => {
			if (this.isShuttingDown) {
				Logger.warn(`Audit Worker: Already shutting down, ignoring ${signal}`);
				return;
			}

			this.isShuttingDown = true;
			Logger.info(`Audit Worker: Received ${signal}, shutting down gracefully...`);

			try {
				// Stop OutboxPoller
				OutboxPoller.stop();
				Logger.info('Audit Worker: OutboxPoller stopped');

				// Close database connection
				await workerSequelize.close();
				Logger.info('Audit Worker: Database connection closed');

				Logger.info('Audit Worker: Shutdown complete');
				process.exit(0);
			} catch (error) {
				Logger.error('Audit Worker: Error during shutdown', error);
				process.exit(1);
			}
		};

		process.on('SIGTERM', () => shutdown('SIGTERM'));
		process.on('SIGINT', () => shutdown('SIGINT'));
		process.on('SIGUSR2', () => shutdown('SIGUSR2'));

		// Handle uncaught errors
		process.on('uncaughtException', (error) => {
			Logger.error('Audit Worker: Uncaught exception', error);
			shutdown('uncaughtException');
		});

		process.on('unhandledRejection', (reason, promise) => {
			Logger.error('Audit Worker: Unhandled rejection', { promise, reason });
			shutdown('unhandledRejection');
		});
	}
}

// Start worker if this file is run directly
if (require.main === module) {
	AuditWorker.start().catch((error) => {
		Logger.error('Audit Worker: Failed to start', error);
		process.exit(1);
	});
}

export default AuditWorker;
