import 'reflect-metadata';
import { createApp } from './app';
import { config } from './config';
import { logger } from './config/logger';
import { prisma } from './config/database';

async function startServer() {
    try {
        // Test database connection
        await prisma.$connect();
        logger.info('Database connected successfully');

        // Create Express app
        const app = createApp();

        // Start server - Listen on all network interfaces
        const server = app.listen(config.port, '0.0.0.0', () => {
            logger.info(`Server running on ${config.appUrl}`)
            logger.info(`Server also accessible at http://0.0.0.0:${config.port}`);
            logger.info(`Environment: ${config.nodeEnv}`);
            logger.info(`Swagger docs available at ${config.appUrl}/api-docs`);
        });

        // Graceful shutdown
        const gracefulShutdown = async (signal: string) => {
            logger.info(`${signal} received, shutting down gracefully`);

            server.close(async () => {
                logger.info('HTTP server closed');

                await prisma.$disconnect();
                logger.info('Database disconnected');

                process.exit(0);
            });

            // Force shutdown after 10 seconds
            setTimeout(() => {
                logger.error('Forced shutdown after timeout');
                process.exit(1);
            }, 10000);
        };

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

    } catch (error) {
        logger.error('Failed to start server', { error });
        process.exit(1);
    }
}

startServer();
