import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { houseService } from "@/services/houses/house.service";

export async function GET(request: Request) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { error: "Vous devez être connecté" },
        { status: 401 }
      );
    }

    const { searchParams } = new URL(request.url);
    const search = searchParams.get("search");
    const include = searchParams.get("include")?.split(",") || [];

    const includeOptions: {
      memberships?: {
        include: {
          user: {
            select: {
              id: boolean;
              username: boolean;
              avatar: boolean;
              score?: boolean;
              level?: boolean;
            };
          };
        };
      };
      creator?: {
        select: {
          id: boolean;
          username: boolean;
          avatar: boolean;
        };
      };
    } = {};
    if (include.includes("members")) {
      includeOptions.memberships = {
        include: {
          user: {
            select: {
              id: true,
              username: true,
              avatar: true,
              score: true,
              level: true,
            },
          },
        },
      };
    }
    if (include.includes("creator")) {
      includeOptions.creator = {
        select: {
          id: true,
          username: true,
          avatar: true,
        },
      };
    }

    let houses;
    if (search) {
      houses = await houseService.searchHouses(search, {
        include: includeOptions,
      });
    } else {
      houses = await houseService.getAllHouses({
        include: includeOptions,
      });
    }

    return NextResponse.json(houses);
  } catch (error) {
    console.error("Error fetching houses:", error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération des maisons" },
      { status: 500 }
    );
  }
}

