import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic'; // No caching

interface ServiceCheck {
  id: string;
  name: string;
  url: string;
  status: 'healthy' | 'degraded' | 'down' | 'maintenance';
  latency: number;
  version?: string;
  uptime?: number;
  message?: string;
  lastChecked: string;
}

interface OpsStatus {
  overall: 'healthy' | 'degraded' | 'critical';
  timestamp: string;
  services: ServiceCheck[];
}

const SERVICES = [
  {
    id: 'backend',
    name: 'Backend API',
    env: 'API_BASE_URL',
    default: 'http://localhost:8000',
    path: '/health',
  },
  {
    id: 'platform',
    name: 'Platform Service',
    env: 'PLATFORM_SERVICE_URL',
    default: 'http://localhost:4003',
    path: '/health',
  },
  {
    id: 'extraction',
    name: 'Extraction Service',
    env: 'EXTRACTION_SERVICE_URL',
    default: 'http://localhost:4005',
    path: '/health',
  },
];

export async function GET() {
  const checks = await Promise.all(
    SERVICES.map(async svc => {
      const baseUrl = process.env[svc.env] || svc.default;
      const url = `${baseUrl}${svc.path}`;
      const start = Date.now();

      try {
        const res = await fetch(url, {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' },
          next: { revalidate: 0 },
          signal: AbortSignal.timeout(3000), // 3s timeout
        });

        const latency = Date.now() - start;

        if (!res.ok) {
          return {
            id: svc.id,
            name: svc.name,
            url,
            status: 'down',
            latency,
            message: `HTTP ${res.status}`,
            lastChecked: new Date().toISOString(),
          } as ServiceCheck;
        }

        const json = await res.json();
        // Assuming standard health response: { status: "ok", version: "0.1.0" }
        // Fastify services return { status: "ok" }
        const isOk = json.status === 'ok';

        return {
          id: svc.id,
          name: svc.name,
          url,
          status: isOk ? 'healthy' : 'degraded',
          latency,
          version: json.version,
          message: isOk ? undefined : JSON.stringify(json),
          lastChecked: new Date().toISOString(),
        } as ServiceCheck;
      } catch (err) {
        return {
          id: svc.id,
          name: svc.name,
          url,
          status: 'down',
          latency: Date.now() - start,
          message: err instanceof Error ? err.message : String(err),
          lastChecked: new Date().toISOString(),
        } as ServiceCheck;
      }
    })
  );

  const downCount = checks.filter(c => c.status === 'down').length;
  const degradedCount = checks.filter(c => c.status === 'degraded').length;

  let overall: OpsStatus['overall'] = 'healthy';
  if (downCount > 0) overall = 'critical';
  else if (degradedCount > 0) overall = 'degraded';

  const response: OpsStatus = {
    overall,
    timestamp: new Date().toISOString(),
    services: checks,
  };

  return NextResponse.json(response);
}
