/**
 * Health Routes
 *
 * Health check and status endpoints.
 */

import { Hono } from 'hono';
import type { AppContext } from '../router.js';
import type { HealthResponse } from '../types.js';

const startTime = Date.now();
const VERSION = '0.1.0';

export const healthRoutes = new Hono<AppContext>();

/**
 * GET /health - Full health check
 */
healthRoutes.get('/', async (c) => {
  const conn = c.get('conn');
  const repoRoot = c.get('repoRoot');

  let dbStatus: HealthResponse['database'] = {
    connected: false,
  };

  if (conn) {
    try {
      const info = await conn.getDatabaseInfo();
      dbStatus = {
        connected: true,
        nodeCount: Object.values(info.nodeCount).reduce((a, b) => a + b, 0),
        relationshipCount: Object.values(info.relCount).reduce((a, b) => a + b, 0),
      };
    } catch (error) {
      dbStatus = {
        connected: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  const response: HealthResponse = {
    status: dbStatus.connected ? 'healthy' : 'starting',
    version: VERSION,
    uptimeSeconds: (Date.now() - startTime) / 1000,
    repoRoot,
    database: dbStatus,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /health/ready - Readiness probe
 */
healthRoutes.get('/ready', async (c) => {
  const conn = c.get('conn');

  if (!conn) {
    return c.json({ ready: false }, 503);
  }

  try {
    await conn.getDatabaseInfo();
    return c.json({ ready: true });
  } catch {
    return c.json({ ready: false }, 503);
  }
});

/**
 * GET /health/live - Liveness probe
 */
healthRoutes.get('/live', (c) => {
  return c.json({ alive: true });
});
