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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ houseId: string }> }
) {
  try {
    const session = await auth();

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

    const { houseId } = await params;

    // Vérifier que l'utilisateur est propriétaire ou admin
    const isAuthorized = await houseService.isUserOwnerOrAdmin(
      session.user.id,
      houseId
    );

    if (!isAuthorized) {
      return NextResponse.json(
        { error: "Vous n'avez pas les permissions pour voir les demandes" },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const status = searchParams.get("status") as "PENDING" | "ACCEPTED" | "REJECTED" | "CANCELLED" | null;

    const requests = await houseService.getHouseRequests(houseId, status || undefined);

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

