import { redirect } from "next/navigation";

import AdminNav from "@/components/admin/AdminNav";
import { readSession } from "@/lib/api/admin-server";

/** Session state is per-request; nothing in here may be cached or prerendered. */
export const dynamic = "force-dynamic";

/**
 * The session guard for every authenticated admin screen (task 3.4).
 *
 * Resolving on the server means an unauthenticated visitor is redirected before any admin
 * markup exists, rather than being shown a dashboard skeleton that empties out once the
 * client discovers there is no session.
 *
 * It also enforces the temporary-password confinement in the only place that can do it for
 * every screen at once. This redirect is a **convenience**, not the rule: the API refuses
 * every admin endpoint under a temporary password on its own authority (design D14), so
 * defeating this would produce a screen full of 403s rather than anybody's guest list.
 * Without it those 403s are what a new host would actually see, which reads as a broken
 * product rather than as "set your password first".
 */
export default async function ProtectedAdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await readSession();
  if (!session) redirect("/admin/signin");
  if (session.must_change_password) redirect("/admin/password");

  return (
    <div className="min-h-dvh bg-stone-50 text-stone-900">
      <AdminNav session={session} />
      <main className="mx-auto w-full max-w-6xl px-4 pb-24 pt-6 sm:px-6">{children}</main>
    </div>
  );
}
