import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

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

/**
 * GET /api/health
 * Health check endpoint — verifies both the server and database are operational.
 * Used by StartOS health checks and Docker health checks.
 * Excluded from auth middleware in middleware.ts.
 */
export async function GET() {
  try {
    // Verify database connectivity with a lightweight query
    const userCount = await prisma.user.count();

    return NextResponse.json({
      status: "ok",
      timestamp: Date.now(),
      database: "connected",
      users: userCount,
    });
  } catch (error) {
    // Server is up but database is unreachable or corrupted
    return NextResponse.json(
      {
        status: "error",
        timestamp: Date.now(),
        database: "disconnected",
        error: error instanceof Error ? error.message : "Unknown database error",
      },
      { status: 503 }
    );
  }
}
