import 'dotenv/config';
import mongoose from 'mongoose';
import NotificationWorkerService from './services/NotificationWorkerService';

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
    console.error('MONGODB_URI is not defined in environment variables');
    process.exit(1);
}

const startWorker = async () => {
    try {
        // Connect to MongoDB first (worker needs DB for appointment lookups)
        await mongoose.connect(MONGODB_URI, {
            maxPoolSize: 10,
            minPoolSize: 2,
        });
        console.log('✓ Worker connected to MongoDB');

        // Initialize the worker AFTER DB connection
        new NotificationWorkerService();

        console.log('✓ Worker process started and listening for jobs');

        // Graceful shutdown
        process.on('SIGTERM', async () => {
            console.log('[Worker] SIGTERM received. Shutting down...');
            await mongoose.disconnect();
            process.exit(0);
        });

        process.on('SIGINT', async () => {
            console.log('[Worker] SIGINT received. Shutting down...');
            await mongoose.disconnect();
            process.exit(0);
        });

    } catch (err) {
        console.error('Worker startup failed:', err);
        process.exit(1);
    }
};

startWorker();
