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

/**
 * Lightweight health check for the critical schema tables required by the
 * admin permission system (admin_users).
 *
 * Used by the deploy workflow as a final post-start gate.
 * Returns 200/JSON on success, 503 on missing table or connection error.
 *
 * This provides the "fail fast with clear message" instead of the previous
 * silent "Access Denied" that only appeared on first admin request.
 */
export async function GET() {
  try {
    // Same check used in the CI verification step and the original error path.
    await pool.query("SELECT 1 FROM admin_users LIMIT 1");
    return NextResponse.json(
      { status: "ok", message: "admin_users table present" },
      { status: 200 }
    );
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Database schema check failed";
    return NextResponse.json(
      {
        status: "error",
        message,
        hint: "Run migrations against the DATABASE_URL (see docs/superpowers/plans/2026-06-prod-db-schema-migration-reliability.md)",
      },
      { status: 503 }
    );
  }
}
