/**
 * Service startup helper — starts the app and logs the address.
 */

import type { FastifyApp, StartOptions } from './types.js';

const registeredSignalHandlers = new Map<string, WeakSet<FastifyApp>>();

export async function startService(app: FastifyApp, options: StartOptions): Promise<void> {
  const { port, host = '0.0.0.0', exitOnFatal = true, registerSignalHandlers = true } = options;

  // Graceful shutdown on SIGTERM/SIGINT (Docker, K8s, Ctrl-C)
  if (registerSignalHandlers) {
    for (const signal of ['SIGTERM', 'SIGINT'] as const) {
      const appsForSignal = registeredSignalHandlers.get(signal) ?? new WeakSet<FastifyApp>();

      if (!appsForSignal.has(app)) {
        appsForSignal.add(app);
        registeredSignalHandlers.set(signal, appsForSignal);

        process.once(signal, async () => {
          app.log.info(`Received ${signal}, shutting down gracefully…`);
          await app.close();
          if (exitOnFatal) {
            process.exit(0);
          }
        });
      }
    }
  }

  try {
    await app.listen({ port, host });
    if (typeof app.setReadyState === 'function') {
      app.setReadyState(true);
    }
    app.log.info(`Service listening on ${host}:${port}`);
  } catch (err) {
    app.log.error(err);
    if (exitOnFatal) {
      process.exit(1);
    }
    throw err;
  }
}
