"use client";
import { useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "./useAuth.js";
const USER_PROFILE_WITH_META_QUERY_KEY = (userId) => ["user-profile-with-meta", userId];
function useUserSettings(options = {}) {
  var _a;
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const { includeMeta = false } = options;
  const {
    data,
    isLoading,
    error: queryError,
    refetch
  } = useQuery({
    queryKey: includeMeta ? USER_PROFILE_WITH_META_QUERY_KEY(user == null ? void 0 : user.id) : ["user-profile", user == null ? void 0 : user.id],
    queryFn: async () => {
      const url = new URL("/api/user/profile", window.location.origin);
      if (includeMeta) {
        url.searchParams.set("includeMeta", "true");
      }
      const response = await fetch(url.toString(), {
        method: "GET",
        credentials: "include"
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to fetch user data");
      }
      return response.json();
    },
    enabled: !!(user == null ? void 0 : user.id),
    staleTime: 5 * 60 * 1e3,
    // 5 minutes - matches useEnsureUserMetadata
    gcTime: 30 * 60 * 1e3
    // 30 minutes cache
  });
  const updateMutation = useMutation({
    mutationFn: async (updates) => {
      const response = await fetch("/api/user/profile", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json"
        },
        credentials: "include",
        body: JSON.stringify(updates)
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to update user settings");
      }
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: USER_PROFILE_WITH_META_QUERY_KEY(user == null ? void 0 : user.id)
      });
      queryClient.invalidateQueries({
        queryKey: ["user-profile", user == null ? void 0 : user.id]
      });
    }
  });
  const updateUserSettings = useCallback(async (updates) => {
    return updateMutation.mutateAsync(updates);
  }, [updateMutation]);
  const error = (queryError == null ? void 0 : queryError.message) || ((_a = updateMutation.error) == null ? void 0 : _a.message) || null;
  return {
    data: data || null,
    isLoading,
    isUpdating: updateMutation.isPending,
    error,
    refetch,
    updateEntity: updateUserSettings
  };
}
function useUserWithMetaSettings() {
  return useUserSettings({ includeMeta: true });
}
export {
  USER_PROFILE_WITH_META_QUERY_KEY,
  useUserSettings,
  useUserWithMetaSettings
};
