import type { FastifyInstance } from 'fastify';
import { checkAllServices, clearHealthCache } from './repository.js';
import { getAllServices, updateService } from '../services/repository.js';
import { requireAdmin, BadRequestError } from '../../lib/auth.js';
import { HealthParamsSchema } from './types.js';

export async function healthRoutes(fastify: FastifyInstance) {
  // Check health of all services
  fastify.get('/health', async (req, reply) => {
    const services = await getAllServices();
    const healthChecks = await checkAllServices(services);

    // Update service status based on health check
    for (const health of healthChecks) {
      await updateService(health.serviceId, {
        status: health.status,
        lastHealthCheckAt: health.lastCheck,
      });
    }

    return reply.send(healthChecks);
  });

  // Check health of specific service
  fastify.get('/health/:serviceId', async (req, reply) => {
    try {
      const params = HealthParamsSchema.parse(req.params);
      const service = await getAllServices().then(services =>
        services.find(s => s.id === params.serviceId)
      );

      if (!service) {
        return reply.code(404).send({ error: 'Service not found' });
      }

      const { checkServiceHealth } = await import('./repository.js');
      const health = await checkServiceHealth(service);

      await updateService(params.serviceId, {
        status: health.status,
        lastHealthCheckAt: health.lastCheck,
      });

      return reply.send(health);
    } catch (error) {
      if (error instanceof Error) {
        throw new BadRequestError(error.message);
      }
      throw error;
    }
  });

  // Clear health cache (admin only)
  fastify.delete('/health/cache', {
    preHandler: async (req) => requireAdmin(req),
  }, async (_req, reply) => {
    clearHealthCache();
    return reply.send({ message: 'Health cache cleared' });
  });
}
