import { notFound } from 'next/navigation';
import type { ReactNode } from 'react';
import { DashboardShell } from '@/components/layout/dashboard-shell';
import { requireGuildAccessOrRedirect } from '@/lib/auth';
import { getManageableGuilds, resolveDashboardGuild } 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 [resolved, guilds, showOwnerLink] = await Promise.all([
    resolveDashboardGuild(session, guildId),
    getManageableGuilds(session),
    isOwnerUser(session.user.id)
  ]);

  if (!resolved) {
    notFound();
  }

  const otherGuilds = guilds.filter((guild) => guild.id !== guildId);

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