/**
 * System Status API Endpoint
 * Returns comprehensive health check results for all system components
 *
 * Security: Rate limited to prevent abuse and DoS attacks
 */

import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { getCachedHealthChecks } from "@/lib/health-checks";
import type { SystemHealth } from "@/lib/types/health";
import { rateLimiters, getClientIdentifier } from "@/lib/rate-limiter";

export const dynamic = "force-dynamic";
export const revalidate = 0;

/**
 * GET /api/status
 * Returns current system health status
 * Rate limited: 20 requests per minute per IP
 */
export async function GET(request: NextRequest) {
  // Apply rate limiting (20 requests per minute)
  try {
    const clientId = getClientIdentifier(request);
    const { success, reset } = await rateLimiters.status.limit(clientId);

    if (!success) {
      const retryAfter = Math.ceil((reset - Date.now()) / 1000);

      return NextResponse.json(
        {
          error: "Rate limit exceeded",
          message: "Too many requests. Please try again later.",
        },
        {
          status: 429,
          headers: {
            "Retry-After": String(retryAfter),
            "Content-Type": "application/json",
          },
        },
      );
    }
  } catch (error) {
    console.error("[RateLimit] Error checking rate limit:", error);
    // Continue even if rate limiting fails
  }
  try {
    const healthStatus: SystemHealth = await getCachedHealthChecks();

    // Set appropriate HTTP status code based on overall health
    const statusCode =
      healthStatus.overall === "operational"
        ? 200
        : healthStatus.overall === "degraded"
          ? 200
          : 503;

    return NextResponse.json(healthStatus, {
      status: statusCode,
      headers: {
        "Cache-Control": "public, max-age=30, s-maxage=30",
        "Content-Type": "application/json",
      },
    });
  } catch (error) {
    // Log error internally but don't expose details to client
    console.error("Health check error:", error);

    return NextResponse.json(
      {
        overall: "down" as const,
        components: [],
        timestamp: new Date().toISOString(),
        // Removed error field to prevent information disclosure
      },
      {
        status: 503,
        headers: {
          "Cache-Control": "no-cache, no-store, must-revalidate",
          "Content-Type": "application/json",
        },
      },
    );
  }
}
