// ABOUTME: HTTP server exposing health check and Prometheus metrics endpoints
// ABOUTME: Provides /health for readiness probes and /metrics for Prometheus scraping

import express from 'express';
import { getMetrics, getMetricsContentType } from './metrics';
import logger from './utils/logger';
import config from './config';

const app = express();
const port = config.observability?.metricsPort || 9090;

// Health check endpoint
app.get('/health', (_req, res) => {
  res.json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    service: 'racing-scraper',
  });
});

// Metrics endpoint for Prometheus
app.get('/metrics', async (_req, res) => {
  try {
    res.set('Content-Type', getMetricsContentType());
    const metrics = await getMetrics();
    res.send(metrics);
  } catch (error) {
    logger.error({ error }, 'Failed to serve metrics');
    res.status(500).send('Error generating metrics');
  }
});

// Start server
export function startServer() {
  app.listen(port, () => {
    logger.info({ port }, 'Metrics server started');
  });
}

// Start if run directly
if (require.main === module) {
  startServer();
}
