import type { ReactNode } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

import { AppShell } from "@/components/layout/AppShell";
import { decodeTokenRole } from "@/lib/auth/session";
import { ADMIN_ROLES, AUTH_COOKIE_NAME } from "@/lib/constants/auth";
import { ROUTES } from "@/lib/constants/routes";

export default async function AdminLayout({
  children,
}: {
  children: ReactNode;
}) {
  const cookieStore = await cookies();
  const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;
  const role = token ? decodeTokenRole(token) : null;

  // proxy.ts already guards /admin/* — this is defense-in-depth for the token
  // expiring between the proxy check and render, and asserts the role actually
  // belongs to the admin panel (proxy checks the same, kept in sync here).
  if (!role) redirect(ROUTES.AUTH.LOGIN);
  if (!ADMIN_ROLES.includes(role)) redirect(ROUTES.SUPPLIER.DASHBOARD);

  return <AppShell role={role}>{children}</AppShell>;
}
