"use client";
import { useEffect, useRef } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { authClient } from "../lib/auth-client.js";
import { USER_PROFILE_WITH_META_QUERY_KEY } from "./useUserSettings.js";
const DEFAULT_METADATA = {
  uiPreferences: {
    theme: "light",
    sidebarCollapsed: false
  },
  securityPreferences: {
    loginAlertsEnabled: true
  },
  notificationsPreferences: {
    pushEnabled: true,
    loginAlertsEmail: true,
    loginAlertsPush: true,
    passwordChangesEmail: true,
    passwordChangesPush: true,
    suspiciousActivityEmail: true,
    suspiciousActivityPush: true,
    mentionsEmail: true,
    mentionsPush: true,
    projectUpdatesEmail: true,
    projectUpdatesPush: false,
    teamInvitesEmail: true,
    teamInvitesPush: true,
    newsletterEmail: false,
    newsletterPush: false,
    promotionsEmail: false,
    promotionsPush: false,
    featureAnnouncementsEmail: true,
    featureAnnouncementsPush: false
  }
};
function useEnsureUserMetadata() {
  var _a, _b;
  const session = authClient.useSession();
  const userId = (_b = (_a = session.data) == null ? void 0 : _a.user) == null ? void 0 : _b.id;
  const queryClient = useQueryClient();
  const hasCreatedMetadata = useRef(false);
  const { data: userData, isFetched } = useQuery({
    queryKey: USER_PROFILE_WITH_META_QUERY_KEY(userId),
    queryFn: async () => {
      const response = await fetch("/api/user/profile?includeMeta=true", {
        credentials: "include"
      });
      if (!response.ok) {
        throw new Error("Failed to fetch user profile");
      }
      return response.json();
    },
    enabled: !!userId,
    staleTime: 5 * 60 * 1e3,
    // 5 minutes - metadata doesn't change often
    gcTime: 30 * 60 * 1e3
    // 30 minutes cache
  });
  const createMetadataMutation = useMutation({
    mutationFn: async () => {
      const response = await fetch("/api/internal/user-metadata", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          userId,
          metadata: DEFAULT_METADATA
        })
      });
      if (!response.ok) {
        throw new Error("Failed to create metadata");
      }
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: USER_PROFILE_WITH_META_QUERY_KEY(userId) });
    },
    onError: (error) => {
      console.error("Error creating user metadata:", error);
    }
  });
  useEffect(() => {
    if (!isFetched || !userData || hasCreatedMetadata.current) return;
    const needsMetadata = !userData.meta || Object.keys(userData.meta).length === 0;
    if (needsMetadata && !createMetadataMutation.isPending) {
      hasCreatedMetadata.current = true;
      console.log("Creating default metadata for user:", userId);
      createMetadataMutation.mutate();
    }
  }, [isFetched, userData, userId, createMetadataMutation]);
}
export {
  useEnsureUserMetadata
};
