import { auth } from "@/auth";
import { redirect, notFound } from "next/navigation";
import { getUserGuilds, getGuildLeaderboard } from "@/lib/discord";
import LeaderboardView from "@/components/LeaderboardView";

export default async function LeaderboardPage({ params }: { params: Promise<{ guildId: string }> }) {
    const session = await auth();
    const { guildId } = await params;

    if (!session?.accessToken) {
        redirect("/");
    }

    const guilds = await getUserGuilds(session.accessToken as string);
    const currentGuild = guilds.find((g) => g.id === guildId);

    if (!currentGuild || !currentGuild.botInGuild) {
        notFound();
    }

    const leaderboardData = await getGuildLeaderboard(currentGuild.id);
    const currentUserRank = leaderboardData.find(m => m.user_id === session?.user?.id);

    return (
        <LeaderboardView
            leaderboardData={leaderboardData}
            currentUserRank={currentUserRank}
            currentUserId={session.user?.id}
        />
    );
}
