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

/**
 * Readiness Probe Endpoint
 *
 * Indicates whether the application is ready to accept traffic
 * Used by load balancers and orchestrators (Kubernetes, DigitalOcean App Platform)
 *
 * Checks:
 * - Convex connectivity (primary datastore)
 *
 * Response Codes:
 * - 200: Ready to accept traffic
 * - 503: Not ready (still initializing or dependencies unavailable)
 */
export async function GET() {
  try {
    const dbHealth = await checkDatabaseHealth();

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

    return NextResponse.json(
      {
        ready: true,
        timestamp: new Date().toISOString(),
        dependencies: {
          convex: "healthy",
        },
      },
      {
        status: 200,
        headers: {
          "Cache-Control": "no-cache, no-store, must-revalidate",
        },
      },
    );
  } catch {
    return NextResponse.json(
      {
        ready: false,
        reason: "Readiness check failed",
        timestamp: new Date().toISOString(),
      },
      { status: 503 },
    );
  }
}
