// src/app/(superadmin)/admin/page.tsx — God-Mode overview (KPIs + recent actions).
// All numbers are live drizzle counts — no mock data.
import { and, count, eq, gt, inArray, notInArray } from "drizzle-orm";
import { getTranslations } from "next-intl/server";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { listAuditLog } from "@/lib/admin/audit";
import { selectOverviewSections } from "@/lib/admin/overview-sections";
import { currentSysPermissions } from "@/lib/auth/sys-permissions";
import { organization, subscription, user } from "@/lib/db/auth-schema";
import { db } from "@/lib/db/client";

// Subscription statuses that grant access (mirror billing/status.ts).
const ACTIVE_SUB_STATUSES = ["active", "trialing", "past_due"] as const;

async function loadUserKpis() {
  const [[totalUsers], [bannedUsers]] = await Promise.all([
    db.select({ v: count() }).from(user),
    db.select({ v: count() }).from(user).where(eq(user.banned, true)),
  ]);
  return {
    totalUsers: totalUsers?.v ?? 0,
    bannedUsers: bannedUsers?.v ?? 0,
  };
}

async function loadOrgKpis() {
  const now = new Date();
  // Orgs that currently hold an access-granting subscription.
  const activeSubOrgIds = db
    .select({ id: subscription.referenceId })
    .from(subscription)
    .where(inArray(subscription.status, [...ACTIVE_SUB_STATUSES]));

  const [[totalOrgs], [trialOrgs]] = await Promise.all([
    db.select({ v: count() }).from(organization),
    db
      .select({ v: count() })
      .from(organization)
      .where(
        and(
          gt(organization.trialEndsAt, now),
          notInArray(organization.id, activeSubOrgIds),
        ),
      ),
  ]);
  return {
    totalOrgs: totalOrgs?.v ?? 0,
    trialOrgs: trialOrgs?.v ?? 0,
  };
}

async function loadBillingKpis() {
  const [[activeSubs]] = await Promise.all([
    db
      .select({ v: count() })
      .from(subscription)
      .where(inArray(subscription.status, [...ACTIVE_SUB_STATUSES])),
  ]);
  return { activeSubs: activeSubs?.v ?? 0 };
}

export default async function AdminOverviewPage() {
  const perms = await currentSysPermissions();
  const sections = selectOverviewSections(perms);

  const [t, userKpis, orgKpis, billingKpis, recent] = await Promise.all([
    getTranslations("SuperAdmin"),
    sections.users ? loadUserKpis() : Promise.resolve(null),
    sections.orgs ? loadOrgKpis() : Promise.resolve(null),
    sections.billing ? loadBillingKpis() : Promise.resolve(null),
    sections.audit ? listAuditLog({ limit: 10 }) : Promise.resolve(null),
  ]);

  const cards = [
    userKpis && { label: t("kpiTotalUsers"), value: userKpis.totalUsers },
    userKpis && { label: t("kpiBannedUsers"), value: userKpis.bannedUsers },
    orgKpis && { label: t("kpiTotalOrgs"), value: orgKpis.totalOrgs },
    billingKpis && {
      label: t("kpiActiveSubs"),
      value: billingKpis.activeSubs,
    },
    orgKpis && { label: t("kpiTrialOrgs"), value: orgKpis.trialOrgs },
  ].filter((c): c is { label: string; value: number } => Boolean(c));

  const hasAnyData = cards.length > 0 || recent !== null;

  const dateFmt = new Intl.DateTimeFormat(undefined, {
    dateStyle: "short",
    timeStyle: "short",
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-semibold text-2xl">{t("overviewTitle")}</h1>
        <p className="text-muted-foreground text-sm">{t("overviewSubtitle")}</p>
      </div>

      {!hasAnyData && (
        <p className="text-muted-foreground text-sm">{t("overviewNoAccess")}</p>
      )}

      {cards.length > 0 && (
        <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-5">
          {cards.map((c) => (
            <Card key={c.label} size="sm">
              <CardHeader>
                <CardDescription>{c.label}</CardDescription>
                <CardTitle className="font-semibold text-3xl tabular-nums">
                  {c.value}
                </CardTitle>
              </CardHeader>
            </Card>
          ))}
        </div>
      )}

      {recent !== null && (
        <Card>
          <CardHeader>
            <CardTitle>{t("recentActionsTitle")}</CardTitle>
            <CardDescription>{t("recentActionsSubtitle")}</CardDescription>
          </CardHeader>
          <CardContent>
            {recent.entries.length === 0 ? (
              <p className="py-6 text-center text-muted-foreground text-sm">
                {t("auditEmpty")}
              </p>
            ) : (
              <ul className="divide-y">
                {recent.entries.map((e) => (
                  <li
                    key={e.id}
                    className="flex items-center justify-between gap-4 py-2 text-sm"
                  >
                    <span className="font-mono text-xs">{e.action}</span>
                    <span className="min-w-0 flex-1 truncate text-muted-foreground">
                      {e.targetLabel ?? e.targetId ?? e.targetType}
                    </span>
                    <span className="shrink-0 text-muted-foreground text-xs">
                      {e.actorEmail}
                    </span>
                    <span className="shrink-0 text-muted-foreground text-xs">
                      {dateFmt.format(e.createdAt)}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}

// Avoid build-time prerender — this page reads live DB + session.
export const dynamic = "force-dynamic";
