import { createFileRoute, redirect } from "@tanstack/react-router";
import { tournamentQueries } from "@/features/tournaments/queries";
import ManageTeams from "@/features/teams/components/manage-teams";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";

export const Route = createFileRoute("/_authed/admin/tournaments/$id/teams")({
  beforeLoad: async ({ context, params }) => {
    const { queryClient } = context;
    const tournament = await ensureServerQueryData(
      queryClient,
      tournamentQueries.details(params.id)
    );
    if (!tournament) throw redirect({ to: "/admin/tournaments" });
    return {
      tournament,
    };
  },
  loader: ({ context }) => ({
    header: {
      withBackButton: true,
      title: `${context.tournament.name} Teams`,
    },
    withPadding: false,
  }),
  component: RouteComponent,
});

function RouteComponent() {
  const { id } = Route.useParams();
  const { tournament } = Route.useRouteContext();
  return <ManageTeams tournament={tournament} />;
}