import Link from 'next/link';
import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { eq } from 'drizzle-orm';
import { ShieldX } from 'lucide-react';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { userProfiles } from '@/lib/db/schema/users';
import { Button } from '@/components/ui/button';

/**
 * Guard: only super-admins (isSuperAdmin === true in user_profiles) may
 * access any page under /[portSlug]/admin.
 *
 * H-15: previously this layout silently redirected non-admins to
 * `/dashboard`, which left them staring at the dashboard with no
 * explanation of why their bookmark / shared admin link "didn't work".
 * Render an explicit 403 page instead so the URL stays on the failed
 * route and the user can see why their request was denied.
 */
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) {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center gap-4 px-4 text-center">
        <div className="flex h-14 w-14 items-center justify-center rounded-full bg-destructive/10">
          <ShieldX className="h-7 w-7 text-destructive" aria-hidden />
        </div>
        <div className="space-y-1">
          <h1 className="text-xl font-semibold">Access denied</h1>
          <p className="max-w-md text-sm text-muted-foreground">
            This area is for super-administrators only. If you believe you should have access, ask
            an administrator to grant the super-admin role on your account.
          </p>
        </div>
        <Button asChild>
          <Link href={`/${portSlug}/dashboard`}>Back to dashboard</Link>
        </Button>
      </div>
    );
  }

  return <>{children}</>;
}
