import HouseManagement from "@/components/admin/HouseManagement";
import { Card } from "@/components/ui";
import { houseService } from "@/services/houses/house.service";
import { Prisma } from "@/prisma/generated/prisma/client";

export const dynamic = "force-dynamic";

export default async function AdminHousesPage() {
  type HouseWithIncludes = Prisma.HouseGetPayload<{
    include: {
      creator: {
        select: {
          id: true;
          username: true;
          avatar: true;
        };
      };
      memberships: {
        include: {
          user: {
            select: {
              id: true;
              username: true;
              avatar: true;
              score: true;
              level: true;
            };
          };
        };
      };
    };
  }>;

  const houses = (await houseService.getAllHouses({
    include: {
      creator: {
        select: {
          id: true,
          username: true,
          avatar: true,
        },
      },
      memberships: {
        include: {
          user: {
            select: {
              id: true,
              username: true,
              avatar: true,
              score: true,
              level: true,
            },
          },
        },
        orderBy: [{ role: "asc" }, { joinedAt: "asc" }],
      },
    },
    orderBy: {
      createdAt: "desc",
    },
  })) as unknown as HouseWithIncludes[];

  // Transformer les données pour la sérialisation
  const serializedHouses = houses.map((house) => ({
    id: house.id,
    name: house.name,
    description: house.description,
    creatorId: house.creatorId,
    creator: house.creator,
    createdAt: house.createdAt.toISOString(),
    updatedAt: house.updatedAt.toISOString(),
    membersCount: house.memberships?.length || 0,
    memberships:
      house.memberships?.map((membership) => ({
        id: membership.id,
        role: membership.role,
        joinedAt: membership.joinedAt.toISOString(),
        user: membership.user,
      })) || [],
  }));

  return (
    <Card variant="dark" className="p-6">
      <h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
        Gestion des Maisons
      </h2>
      <HouseManagement initialHouses={serializedHouses} />
    </Card>
  );
}
