/**
 * Health Check API
 * GET /api/transparency/health
 *
 * Returns the health status of all transparency components.
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransparencyDashboard, getAuditLog } from '../../../lib/transparency';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const dashboard = getTransparencyDashboard();
    const auditLog = getAuditLog();

    const health = await dashboard.getSystemHealth();
    const auditIntegrity = auditLog.verifyIntegrity();

    const response = {
      status: health.status,
      timestamp: new Date().toISOString(),
      uptime: health.uptime,
      components: health.components,
      auditIntegrity: {
        valid: auditIntegrity.valid,
        errorCount: auditIntegrity.errors.length
      }
    };

    // Set appropriate status code based on health
    const statusCode = health.status === 'healthy' ? 200 :
      health.status === 'degraded' ? 200 : 503;

    return res.status(statusCode).json(response);
  } catch (error) {
    console.error('[API] Health check error:', error);
    return res.status(503).json({
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      error: 'Health check failed'
    });
  }
}
