import app from './app.js';
import dotenv from 'dotenv';
import { migrateFilesToGridFS } from './services/dataSheetService.js';
import { connectDB } from './config/database.js';
import mongoose from 'mongoose';
import { notificationService } from './services/notificationService.js';

dotenv.config();

const startServer = async () => {
    try {
        await connectDB();

        const PORT = process.env.PORT || 3000;
        app.listen(Number(PORT), '0.0.0.0', async () => {
            console.log(`🚀 Server running on port ${PORT} (0.0.0.0)`);
            if (mongoose.connection.readyState === 1) {
                // await migrateFilesToGridFS().catch(err => console.error('Migration failed:', err));

                // Agendar verificação de vencimento de estoque (a cada 24 horas)
                console.log('📅 Scheduling stock expiration check...');
                setInterval(() => {
                    notificationService.checkStockExpirations();
                }, 24 * 60 * 60 * 1000);

                // Executar uma vez no início para garantir (opcional, bom para dev)
                notificationService.checkStockExpirations();

            } else {
                console.warn('⚠️ MongoDB is not connected. Skipping migrations.');
            }
        });
    } catch (error) {
        console.error('Failed to start server:', error);
    }
};

startServer();

// Force keep-alive to debug why it exits
setInterval(() => { }, 1000);
