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

/**
 * Dev-only: verifies Prisma can connect (NextAuth adapter needs this after Google redirects back).
 * Open GET /api/debug/prisma while running next dev.
 */
export async function GET() {
  if (process.env.NODE_ENV !== "development") {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const hasUrl = Boolean(process.env.DATABASE_URL?.trim() || process.env.POSTGRES_URL?.trim());
  const prisma = new PrismaClient();
  try {
    await prisma.$queryRaw`SELECT 1`;
    return NextResponse.json({
      ok: true,
      databaseUrlConfigured: hasUrl,
      hint: "Prisma connects; if auth still fails, check Google client id/secret and terminal [next-auth] logs.",
    });
  } catch (e: unknown) {
    const message = e instanceof Error ? e.message : "Unknown error";
    const publicHost = /Can't reach database server at `([\d.]+):(\d+)`/.exec(message);
    const hint = publicHost
      ? `No TCP route to Postgres at ${publicHost[1]}:${publicHost[2]} from this machine. In Coolify: confirm the DB service publishes that host port and Postgres listens on 0.0.0.0. On the cloud firewall (e.g. GCP), allow inbound TCP ${publicHost[2]} from your IP (or use VPN). Test: nc -zv ${publicHost[1]} ${publicHost[2]} or psql. Then npm run db:push from vibn-frontend.`
      : "If the URL uses a Coolify internal hostname, it only works inside Docker. Otherwise check DATABASE_URL, firewall, and run npm run db:push.";
    return NextResponse.json(
      {
        ok: false,
        databaseUrlConfigured: hasUrl,
        message,
        hint,
      },
      { status: 500 }
    );
  } finally {
    await prisma.$disconnect().catch(() => {});
  }
}
