import { Router, Request, Response } from 'express';
import { prisma } from '../../lib/prisma';
import { authenticate } from '../../middleware/auth';
const router = Router();

// Public health endpoint for CCP itself
router.get('/', async (_req: Request, res: Response) => {
  try {
    await prisma.$queryRaw`SELECT 1`;
    res.json({ status: 'healthy', timestamp: new Date().toISOString() });
  } catch {
    res.status(503).json({ status: 'unhealthy', timestamp: new Date().toISOString() });
  }
});

// Authenticated: overview of all instances' health
router.get('/overview', authenticate, async (_req: Request, res: Response) => {
  const instances = await prisma.instance.findMany({
    select: {
      id: true,
      name: true,
      slug: true,
      domain: true,
      status: true,
      lastHealthCheck: true,
      healthChecks: {
        orderBy: { checkedAt: 'desc' },
        take: 1,
      },
    },
  });

  const summary = instances.map((i) => ({
    id: i.id,
    name: i.name,
    slug: i.slug,
    domain: i.domain,
    status: i.status,
    lastHealthCheck: i.lastHealthCheck,
    health: i.healthChecks[0] || null,
  }));

  res.json({ data: summary });
});

export default router;
