"use client";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "./useAuth.js";
import { fetchWithTeam } from "../lib/api/entities.js";
function useEntityQuery(options) {
  var _a, _b, _c;
  const {
    entityConfig,
    pageSize = 10,
    includeChildren = false,
    search = "",
    filters = {},
    sort = null,
    enabled = true,
    staleTime = 1e3 * 60 * 5,
    // 5 minutes default
    gcTime = 1e3 * 60 * 60
    // 1 hour default
  } = options;
  const { user } = useAuth();
  const activeTeamId = typeof window !== "undefined" ? localStorage.getItem("activeTeamId") : null;
  const queryKey = [
    "entity",
    entityConfig.slug,
    activeTeamId,
    {
      pageSize,
      includeChildren,
      search,
      filters,
      sort
    }
  ];
  const query = useQuery({
    queryKey,
    queryFn: async () => {
      var _a2;
      const queryParams = {
        limit: String(pageSize)
      };
      if (search) queryParams.search = search;
      if (includeChildren) queryParams.child = "all";
      if (sort) {
        queryParams.sortBy = sort.field;
        queryParams.sortOrder = sort.direction;
      }
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== void 0 && value !== null) {
          queryParams[key] = String(value);
        }
      });
      const params = new URLSearchParams(queryParams);
      const url = `/api/v1/${entityConfig.slug}?${params.toString()}`;
      const response = await fetchWithTeam(url);
      if (!response.ok) {
        if (response.status === 400) {
          const errorData = await response.json().catch(() => ({}));
          if (errorData.code === "TEAM_CONTEXT_REQUIRED") {
            console.warn("[useEntityQuery] Team context not ready yet, returning empty list");
            return { items: [], total: 0, page: 1, totalPages: 0 };
          }
        }
        throw new Error(`Failed to fetch ${entityConfig.names.plural}`);
      }
      const data = await response.json();
      return {
        items: data.items || data.data || data[entityConfig.slug] || [],
        total: data.total || ((_a2 = data.info) == null ? void 0 : _a2.total) || 0,
        page: data.page || 1,
        totalPages: Math.ceil((data.total || 0) / pageSize)
      };
    },
    enabled: enabled && !!user,
    staleTime,
    gcTime
  });
  return {
    ...query,
    items: ((_a = query.data) == null ? void 0 : _a.items) || [],
    total: ((_b = query.data) == null ? void 0 : _b.total) || 0,
    totalPages: ((_c = query.data) == null ? void 0 : _c.totalPages) || 1
  };
}
function useEntityOne(entityConfig, id, options = {}) {
  const { user } = useAuth();
  const { includeChildren = false, enabled = true } = options;
  const activeTeamId = typeof window !== "undefined" ? localStorage.getItem("activeTeamId") : null;
  const queryKey = ["entity", entityConfig.slug, activeTeamId, id, { includeChildren }];
  return useQuery({
    queryKey,
    queryFn: async () => {
      const params = includeChildren ? "?child=all" : "";
      const url = `/api/v1/${entityConfig.slug}/${id}${params}`;
      const response = await fetchWithTeam(url);
      if (!response.ok) {
        if (response.status === 404) {
          throw new Error(`${entityConfig.names.singular} not found`);
        }
        if (response.status === 400) {
          const errorData = await response.json().catch(() => ({}));
          if (errorData.code === "TEAM_CONTEXT_REQUIRED") {
            console.warn("[useEntityOne] Team context not ready yet, returning null");
            return null;
          }
        }
        throw new Error(`Failed to fetch ${entityConfig.names.singular}`);
      }
      const data = await response.json();
      return data.data || data.item || data;
    },
    enabled: enabled && !!user && !!id,
    staleTime: 1e3 * 60 * 5,
    gcTime: 1e3 * 60 * 60
  });
}
export {
  useEntityOne,
  useEntityQuery
};
