import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { eq } from 'drizzle-orm';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { userProfiles } from '@/lib/db/schema/users';

/**
 * Guard: only super-admins (isSuperAdmin === true in user_profiles) may access
 * any page under /[portSlug]/admin. Everyone else is redirected to their dashboard.
 */
export default async function AdminLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ portSlug: string }>;
}) {
  const { portSlug } = await params;
  const session = await auth.api.getSession({ headers: await headers() });

  if (!session?.user) {
    redirect('/login');
  }

  const profile = await db.query.userProfiles.findFirst({
    where: eq(userProfiles.userId, session.user.id),
  });

  if (!profile?.isSuperAdmin) {
    redirect(`/${portSlug}/dashboard`);
  }

  return <>{children}</>;
}
