import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { getBackgroundImage } from "@/lib/preferences";
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
import HousesSection from "@/components/houses/HousesSection";
import { houseService } from "@/services/houses/house.service";
import { userService } from "@/services/users/user.service";

export const dynamic = "force-dynamic";

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

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

  const [housesData, myHouseData, invitationsData, users, backgroundImage] = await Promise.all([
    // Récupérer les maisons
    houseService.getAllHouses({
      include: {
        memberships: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                avatar: true,
                score: true,
                level: true,
              },
            },
          },
          orderBy: [
            { role: "asc" }, // OWNER, ADMIN, MEMBER
            { user: { score: "desc" } }, // Puis par score décroissant
          ],
        },
        creator: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
      },
    }),
    // Récupérer la maison de l'utilisateur
    houseService.getUserHouse(session.user.id, {
      memberships: {
        include: {
          user: {
            select: {
              id: true,
              username: true,
              avatar: true,
              score: true,
              level: true,
            },
          },
        },
      },
      creator: {
        select: {
          id: true,
          username: true,
          avatar: true,
        },
      },
    }),
    // Récupérer les invitations de l'utilisateur
    houseService.getUserInvitations(session.user.id, "PENDING"),
    // Récupérer tous les utilisateurs pour les invitations
    userService.getAllUsers({
      select: {
        id: true,
        username: true,
        avatar: true,
      },
    }),
    getBackgroundImage("challenges", "/got-2.jpg"),
  ]);

  // Sérialiser les données pour le client
  const houses = (housesData as any[]).map((house: any) => ({
    id: house.id,
    name: house.name,
    description: house.description,
    creator: house.creator || { id: house.creatorId, username: "Unknown", avatar: null },
    memberships: (house.memberships || []).map((m: any) => ({
      id: m.id,
      role: m.role,
      user: {
        id: m.user.id,
        username: m.user.username,
        avatar: m.user.avatar,
        score: m.user.score ?? 0,
        level: m.user.level ?? 1,
      },
    })),
  }));

  const myHouse = myHouseData
    ? {
        id: myHouseData.id,
        name: myHouseData.name,
        description: myHouseData.description,
        creator: (myHouseData as any).creator || { id: (myHouseData as any).creatorId, username: "Unknown", avatar: null },
        memberships: ((myHouseData as any).memberships || []).map((m: any) => ({
          id: m.id,
          role: m.role,
          user: {
            id: m.user.id,
            username: m.user.username,
            avatar: m.user.avatar,
            score: m.user.score ?? 0,
            level: m.user.level ?? 1,
          },
        })),
      }
    : null;

  const invitations = invitationsData.map((inv: any) => ({
    id: inv.id,
    house: {
      id: inv.house.id,
      name: inv.house.name,
    },
    inviter: inv.inviter,
    status: inv.status,
    createdAt: inv.createdAt.toISOString(),
  }));

  return (
    <main className="min-h-screen bg-black relative">
      <NavigationWrapper />
      <HousesSection
        initialHouses={houses}
        initialMyHouse={myHouse}
        initialUsers={users}
        initialInvitations={invitations}
        backgroundImage={backgroundImage}
      />
    </main>
  );
}
