import 'dotenv/config';
import { createApp } from './app';
import { checkConnection, closePool } from './db/pool';
import logger from './logger';

async function main() {
  const connected = await checkConnection();
  if (!connected) {
    logger.error('Failed to connect to database');
    process.exit(1);
  }

  const PORT = Number(process.env.PORT) || 3000;
  const app = createApp();
  const server = app.listen(PORT, () => {
    logger.info(`Server running on http://localhost:${PORT}`);
  });

  function shutdown(signal: string) {
    logger.info(`${signal} received — shutting down...`);
    server.close(async () => {
      await closePool();
      logger.info('All connections closed. Exiting.');
      process.exit(0);
    });
  }

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

main().catch(err => {
  logger.error(err);
  process.exit(1);
});
