import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { getBackgroundImage } from "@/lib/preferences";
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
import ChallengesSection from "@/components/challenges/ChallengesSection";
import { challengeService } from "@/services/challenges/challenge.service";
import { userService } from "@/services/users/user.service";

export const dynamic = "force-dynamic";

export default async function ChallengesPage() {
  const session = await auth();

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

  const [challengesRaw, users, backgroundImage] = await Promise.all([
    challengeService.getUserChallenges(session.user.id),
    userService
      .getAllUsers({
        orderBy: {
          username: "asc",
        },
        select: {
          id: true,
          username: true,
          avatar: true,
          score: true,
          level: true,
        },
      })
      .then((users) => users.filter((user) => user.id !== session.user.id)),
    getBackgroundImage("challenges", "/got-2.jpg"),
  ]);

  // Convertir les dates Date en string pour correspondre au type attendu par le composant
  const challenges = challengesRaw.map((challenge) => ({
    ...challenge,
    createdAt: challenge.createdAt.toISOString(),
    acceptedAt: challenge.acceptedAt?.toISOString() ?? null,
    completedAt: challenge.completedAt?.toISOString() ?? null,
  }));

  return (
    <main className="min-h-screen bg-black relative">
      <NavigationWrapper />
      <ChallengesSection
        initialChallenges={challenges}
        initialUsers={users}
        backgroundImage={backgroundImage}
      />
    </main>
  );
}
