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

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

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

  // Graceful shutdown on SIGTERM/SIGINT (Docker, K8s, Ctrl-C)
  for (const signal of ['SIGTERM', 'SIGINT'] as const) {
    process.on(signal, async () => {
      app.log.info(`Received ${signal}, shutting down gracefully…`);
      await app.close();
      process.exit(0);
    });
  }

  try {
    await app.listen({ port, host });
    app.log.info(`Service listening on ${host}:${port}`);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
}
