import { notFound } from 'next/navigation';
import type { ReactNode } from 'react';
import { DashboardShell } from '@/components/layout/dashboard-shell';
import { requireGuildAccessOrRedirect } from '@/lib/auth';
import { getManageableGuilds } from '@/lib/guilds';
import { isOwnerUser } from '@/lib/owner-auth';

interface GuildLayoutProps {
  children: ReactNode;
  params: Promise<{ guildId: string }>;
}

export default async function GuildLayout({ children, params }: GuildLayoutProps) {
  const { guildId } = await params;
  const session = await requireGuildAccessOrRedirect(guildId);
  const guilds = await getManageableGuilds(session);
  const currentGuild = guilds.find((guild) => guild.id === guildId);

  if (!currentGuild) {
    notFound();
  }

  const otherGuilds = guilds.filter((guild) => guild.id !== guildId);
  const showOwnerLink = await isOwnerUser(session.user.id);

  return (
    <DashboardShell
      guildId={guildId}
      currentGuild={currentGuild}
      otherGuilds={otherGuilds}
      user={session.user}
      showOwnerLink={showOwnerLink}
    >
      {children}
    </DashboardShell>
  );
}
