import Fastify from 'fastify';
import { app } from './app/app';
import { logger } from './app/utils/logger';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : 12321;

// Global error handlers
process.on('uncaughtException', (error: Error) => {
  void logger.error('Uncaught Exception', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason: unknown) => {
  const error = reason instanceof Error ? reason : new Error(String(reason));
  void logger.error('Unhandled Rejection', error);
  process.exit(1);
});

process.on('warning', (warning: Error) => {
  void logger.log('warn', `Process Warning: ${warning.name} - ${warning.message}`);
});

process.on('SIGTERM', () => {
  void logger.log('info', 'SIGTERM signal received: closing HTTP server');
  server.close(() => {
    void logger.log('info', 'HTTP server closed');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  void logger.log('info', 'SIGINT signal received: closing HTTP server');
  server.close(() => {
    void logger.log('info', 'HTTP server closed');
    process.exit(0);
  });
});

// Instantiate Fastify with some config
const server = Fastify({
  logger: true,
  bodyLimit: 10485760, // 10MB max body size (to accommodate base64-encoded images)
});

// Register your application as a normal plugin.
server.register(app);

// Start listening.
server.listen({ port, host }, (err) => {
  if (err) {
    server.log.error(err);
    process.exit(1);
  } else {
    void logger.log('info', `Server ready at http://${host}:${port}`);
  }
});
