import { notFound } from "next/navigation";
import { PageShell } from "@/components/app/page-shell";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { requireOnboardedUser } from "@/lib/auth/user";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export default async function DevDbPage() {
  if (process.env.NODE_ENV !== "development") {
    notFound();
  }

  await requireOnboardedUser();

  let counts: { label: string; value: number }[] = [];
  let dbError: string | null = null;

  try {
    const [modules, questions, options, recommendations, pages] = await Promise.all([
      prisma.diagnosticModule.count(),
      prisma.question.count(),
      prisma.answerOption.count(),
      prisma.recommendation.count(),
      prisma.contentPage.count(),
    ]);

    counts = [
      { label: "Diagnostic Modules", value: modules },
      { label: "Questions", value: questions },
      { label: "Answer Options", value: options },
      { label: "Recommendations", value: recommendations },
      { label: "Content Pages", value: pages },
    ];
  } catch (error) {
    dbError = error instanceof Error ? error.message : "Unknown database connection error.";
  }

  return (
    <PageShell title="Dev DB Viewer" description="Development-only route for quick seeded data checks.">
      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Database Snapshot</h2>
        </CardHeader>
        <CardContent>
          {dbError ? (
            <p className="rounded-lg border border-[#f6d0d0] bg-[#fff3f3] p-3 text-sm text-[#9d3030]">
              DB connection unavailable: {dbError}
            </p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {counts.map((item) => (
                <div key={item.label} className="rounded-xl border border-[#dde5f2] bg-[#f8faff] p-4">
                  <p className="text-xs font-semibold uppercase text-[#5f6d86]">{item.label}</p>
                  <p className="mt-1 text-2xl font-bold text-[#1e2b45]">{item.value}</p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </PageShell>
  );
}
