import { NextResponse } from "next/server";
import { checkDatabaseHealth } from "@/lib/health-checks";

/**
 * Startup Probe Endpoint
 *
 * Indicates whether the application has completed startup
 * Used by orchestrators during initial container startup
 *
 * Checks if critical systems are initialized:
 * - Database connection pool ready
 * - Environment variables loaded
 * - Application fully initialized
 *
 * Response Codes:
 * - 200: Startup complete, ready for traffic
 * - 503: Still starting up
 */

// Track startup completion
let startupComplete = false;
let startupError: string | null = null;

export async function GET() {
  try {
    // If already verified as started, return quickly
    if (startupComplete) {
      return NextResponse.json(
        {
          started: true,
          timestamp: new Date().toISOString(),
          uptime: process.uptime(),
        },
        { status: 200 },
      );
    }

    // Check if critical systems are available
    const dbHealth = await checkDatabaseHealth();

    if (!dbHealth.healthy) {
      startupError = "Database not available";
      return NextResponse.json(
        {
          started: false,
          reason: startupError,
          timestamp: new Date().toISOString(),
        },
        { status: 503 },
      );
    }

    // Check environment variables (Convex deployment)
    const requiredEnvVars = [
      "NEXT_PUBLIC_CONVEX_URL",
      "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY",
    ];

    const missingEnvVars = requiredEnvVars.filter(
      (varName) => !process.env[varName],
    );

    if (missingEnvVars.length > 0) {
      startupError = `Missing environment variables: ${missingEnvVars.join(", ")}`;
      return NextResponse.json(
        {
          started: false,
          reason: startupError,
          timestamp: new Date().toISOString(),
        },
        { status: 503 },
      );
    }

    // All checks passed - mark as started
    startupComplete = true;
    startupError = null;

    return NextResponse.json(
      {
        started: true,
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
      },
      {
        status: 200,
        headers: {
          "Cache-Control": "no-cache, no-store, must-revalidate",
        },
      },
    );
  } catch {
    startupError = "Startup check failed";
    return NextResponse.json(
      {
        started: false,
        reason: startupError,
        timestamp: new Date().toISOString(),
      },
      { status: 503 },
    );
  }
}
