import { NextResponse } from "next/server"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

export async function GET() {
  const diagnostics: Record<string, unknown> = {
    timestamp: new Date().toISOString(),
    nodeVersion: process.version,
    platform: process.platform,
    arch: process.arch,
    env: {
      NODE_ENV: process.env.NODE_ENV,
      BETTER_AUTH_URL: process.env.BETTER_AUTH_URL ? "set" : "not set",
      NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL ? "set" : "not set",
      DATABASE_URL: process.env.DATABASE_URL ? "set" : "not set",
      BETTER_AUTH_SECRET: process.env.BETTER_AUTH_SECRET ? "set" : "not set",
    },
  }

  // Test PostgreSQL connection via Prisma
  try {
    const { prisma } = await import("@/lib/prisma")
    await prisma.$queryRaw`SELECT 1`
    diagnostics.postgres = { status: "ok", message: "PostgreSQL connection works" }
  } catch (error) {
    diagnostics.postgres = {
      status: "error",
      message: error instanceof Error ? error.message : String(error),
    }
  }

  // Test auth config
  try {
    const { auth } = await import("@/lib/auth")
    diagnostics.auth = {
      status: "ok",
      baseURL: (auth as { options?: { baseURL?: string } }).options?.baseURL ?? "unknown",
      trustedOrigins: "configured",
    }
  } catch (error) {
    diagnostics.auth = {
      status: "error",
      message: error instanceof Error ? error.message : String(error),
    }
  }

  const hasErrors = Object.values(diagnostics).some(
    (v) => typeof v === "object" && v !== null && "status" in v && v.status === "error"
  )

  return NextResponse.json(diagnostics, {
    status: hasErrors ? 500 : 200,
  })
}
