import Fastify from 'fastify';
import { config } from './config.js';
import { shutdownPools } from './db/pool.js';
import { startListener, stopListener } from './db/notify.js';
import { registerWs } from './ws/server.js';
import { connectRedis, redis } from './qmanager/cache.js';
import { startInvalidator } from './qmanager/invalidator.js';

async function main(): Promise<void> {
  const app = Fastify({ logger: { level: 'info' } });

  app.get('/health', async () => ({ ok: true, ts: new Date().toISOString() }));

  await registerWs(app);

  await connectRedis();
  await startListener();
  startInvalidator();

  await app.listen({ port: config.http.port, host: '0.0.0.0' });
  app.log.info(`mocl-server up on :${config.http.port} (ws ${config.http.wsPath})`);

  const shutdown = async (sig: string): Promise<void> => {
    app.log.info(`got ${sig}, shutting down`);
    try { await app.close(); } catch (e) { app.log.error(e); }
    try { await stopListener(); } catch (e) { app.log.error(e); }
    try { await shutdownPools(); } catch (e) { app.log.error(e); }
    try { await redis.quit(); } catch (e) { app.log.error(e); }
    process.exit(0);
  };
  process.on('SIGINT',  () => void shutdown('SIGINT'));
  process.on('SIGTERM', () => void shutdown('SIGTERM'));
}

main().catch(err => {
  console.error('fatal', err);
  process.exit(1);
});
