import { notFound, redirect } from 'next/navigation';

import { PlayersList } from '@/components/PlayersList';
import { getPlayersForTournamentPaged, PLAYERS_PAGE_SIZE } from '@/lib/data';

export const dynamic = 'force-dynamic';

type PageProps = {
  params: Promise<{ tournament_key: string }>;
  searchParams: Promise<{ page?: string }>;
};

export default async function TournamentPlayersPage({ params, searchParams }: PageProps) {
  const { tournament_key } = await params;
  const { page: pageRaw } = await searchParams;
  const parsed = parseInt(pageRaw ?? '1', 10);
  const page = Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 1;

  const result = await getPlayersForTournamentPaged(tournament_key, page);
  if (result === null) {
    notFound();
  }

  const { players, total } = result;
  const totalPages = Math.max(1, Math.ceil(total / PLAYERS_PAGE_SIZE));
  const basePath = `/tournaments/${encodeURIComponent(tournament_key)}/players`;

  if (page > totalPages) {
    redirect(totalPages <= 1 ? basePath : `${basePath}?page=${totalPages}`);
  }

  return (
    <PlayersList
      players={players}
      pagination={{
        page,
        total,
        pageSize: PLAYERS_PAGE_SIZE,
        basePath,
      }}
    />
  );
}
