import { useQuery } from "@tanstack/react-query";
import { PropertyWithRelations } from "@/app/db/schema/property";
import { FilterGroups } from "@/app/utils/propertyFilters";

interface Params {
  portfolioId: string;
  filterGroups: FilterGroups;
}

export interface PropertiesResponse {
  data: PropertyWithRelations[];
  total: number | null; // null when fetched with offset > 0 (count not recomputed)
}

export function useProperties({ portfolioId, filterGroups }: Params) {
  return useQuery<PropertiesResponse>({
    queryKey: ["properties", portfolioId, filterGroups],
    queryFn: async () => {
      const res = await fetch("/api/properties", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          portfolioId,
          filters: filterGroups,
        }),
      });

      if (!res.ok) throw new Error("Failed to fetch properties");
      return res.json();
    },
    staleTime: 1000 * 60 * 5, // 5 minutes
    cacheTime: 1000 * 60 * 30, // 30 minutes

    refetchOnMount: false,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
    keepPreviousData: true,
  });
}
