"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useUploadAvatar = exports.useUpdateProfile = exports.useUpdateAccountSettings = void 0;
var _reactQuery = require("@tanstack/react-query");
var _queryKeys = require("../queries/queryKeys");
var _OxyContext = require("../../context/OxyContext");
var _sonner = require("../../../lib/sonner");
/**
 * Update user profile with optimistic updates and offline queue support
 */
const useUpdateProfile = () => {
  const {
    oxyServices,
    activeSessionId,
    user,
    syncIdentity
  } = (0, _OxyContext.useOxy)();
  const queryClient = (0, _reactQuery.useQueryClient)();
  return (0, _reactQuery.useMutation)({
    mutationFn: async updates => {
      // Ensure we have a valid token before making the request
      if (!oxyServices.hasValidToken() && activeSessionId) {
        try {
          // Try to get token for the session
          await oxyServices.getTokenBySession(activeSessionId);
        } catch (tokenError) {
          // If getting token fails, might be an offline session - try syncing
          const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
          if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
            try {
              await syncIdentity();
              // Retry getting token after sync
              await oxyServices.getTokenBySession(activeSessionId);
            } catch (syncError) {
              throw new Error('Session needs to be synced. Please try again.');
            }
          } else {
            throw tokenError;
          }
        }
      }
      try {
        return await oxyServices.updateProfile(updates);
      } catch (error) {
        const errorMessage = error?.message || '';
        const status = error?.status || error?.response?.status;

        // Handle authentication errors
        if (status === 401 || errorMessage.includes('Authentication required') || errorMessage.includes('Invalid or missing authorization header')) {
          // Try to sync session and get token
          if (activeSessionId) {
            try {
              await syncIdentity();
              await oxyServices.getTokenBySession(activeSessionId);
              // Retry the update after getting token
              return await oxyServices.updateProfile(updates);
            } catch (retryError) {
              throw new Error('Authentication failed. Please sign in again.');
            }
          } else {
            throw new Error('No active session. Please sign in.');
          }
        }

        // TanStack Query will automatically retry on network errors
        throw error;
      }
    },
    // Optimistic update
    onMutate: async updates => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({
        queryKey: _queryKeys.queryKeys.accounts.current()
      });

      // Snapshot previous value
      const previousUser = queryClient.getQueryData(_queryKeys.queryKeys.accounts.current());

      // Optimistically update
      if (previousUser) {
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), {
          ...previousUser,
          ...updates
        });

        // Also update profile query if sessionId is available
        if (activeSessionId) {
          queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), {
            ...previousUser,
            ...updates
          });
        }
      }
      return {
        previousUser
      };
    },
    // On error, rollback
    onError: (error, updates, context) => {
      if (context?.previousUser) {
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), context.previousUser);
        if (activeSessionId) {
          queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), context.previousUser);
        }
      }
      _sonner.toast.error(error instanceof Error ? error.message : 'Failed to update profile');
    },
    // On success, invalidate and refetch
    onSuccess: data => {
      // Update cache with server response
      queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), data);
      if (activeSessionId) {
        queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), data);
      }

      // Invalidate related queries
      (0, _queryKeys.invalidateUserQueries)(queryClient);
    },
    // Always refetch after error or success
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: _queryKeys.queryKeys.accounts.current()
      });
      if (activeSessionId) {
        queryClient.invalidateQueries({
          queryKey: _queryKeys.queryKeys.users.profile(activeSessionId)
        });
      }
    }
  });
};

/**
 * Upload avatar with progress tracking and offline queue support
 */
exports.useUpdateProfile = useUpdateProfile;
const useUploadAvatar = () => {
  const {
    oxyServices,
    activeSessionId,
    syncIdentity
  } = (0, _OxyContext.useOxy)();
  const queryClient = (0, _reactQuery.useQueryClient)();
  return (0, _reactQuery.useMutation)({
    mutationFn: async file => {
      // Ensure we have a valid token before making the request
      if (!oxyServices.hasValidToken() && activeSessionId) {
        try {
          await oxyServices.getTokenBySession(activeSessionId);
        } catch (tokenError) {
          const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
          if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
            try {
              await syncIdentity();
              await oxyServices.getTokenBySession(activeSessionId);
            } catch (syncError) {
              throw new Error('Session needs to be synced. Please try again.');
            }
          } else {
            throw tokenError;
          }
        }
      }
      try {
        // Upload file first
        const uploadResult = await oxyServices.assetUpload(file, 'public');
        const fileId = uploadResult?.file?.id || uploadResult?.id || uploadResult;
        if (!fileId || typeof fileId !== 'string') {
          throw new Error('Failed to get file ID from upload result');
        }

        // Update profile with file ID
        return await oxyServices.updateProfile({
          avatar: fileId
        });
      } catch (error) {
        const errorMessage = error?.message || '';
        const status = error?.status || error?.response?.status;

        // Handle authentication errors
        if (status === 401 || errorMessage.includes('Authentication required') || errorMessage.includes('Invalid or missing authorization header')) {
          if (activeSessionId) {
            try {
              await syncIdentity();
              await oxyServices.getTokenBySession(activeSessionId);
              // Retry upload
              const uploadResult = await oxyServices.assetUpload(file, 'public');
              const fileId = uploadResult?.file?.id || uploadResult?.id || uploadResult;
              if (!fileId || typeof fileId !== 'string') {
                throw new Error('Failed to get file ID from upload result');
              }
              return await oxyServices.updateProfile({
                avatar: fileId
              });
            } catch (retryError) {
              throw new Error('Authentication failed. Please sign in again.');
            }
          } else {
            throw new Error('No active session. Please sign in.');
          }
        }

        // TanStack Query will automatically retry on network errors
        throw error;
      }
    },
    onMutate: async file => {
      await queryClient.cancelQueries({
        queryKey: _queryKeys.queryKeys.accounts.current()
      });
      const previousUser = queryClient.getQueryData(_queryKeys.queryKeys.accounts.current());

      // Optimistically set a temporary avatar (using file URI as placeholder)
      if (previousUser) {
        const optimisticUser = {
          ...previousUser,
          avatar: file.uri // Temporary, will be replaced with fileId
        };
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), optimisticUser);
        if (activeSessionId) {
          queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), optimisticUser);
        }
      }
      return {
        previousUser
      };
    },
    onError: (error, file, context) => {
      if (context?.previousUser) {
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), context.previousUser);
        if (activeSessionId) {
          queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), context.previousUser);
        }
      }
      _sonner.toast.error(error instanceof Error ? error.message : 'Failed to upload avatar');
    },
    onSuccess: data => {
      queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), data);
      if (activeSessionId) {
        queryClient.setQueryData(_queryKeys.queryKeys.users.profile(activeSessionId), data);
      }
      (0, _queryKeys.invalidateUserQueries)(queryClient);
      _sonner.toast.success('Avatar updated successfully');
    },
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: _queryKeys.queryKeys.accounts.current()
      });
      if (activeSessionId) {
        queryClient.invalidateQueries({
          queryKey: _queryKeys.queryKeys.users.profile(activeSessionId)
        });
      }
    }
  });
};

/**
 * Update account settings
 */
exports.useUploadAvatar = useUploadAvatar;
const useUpdateAccountSettings = () => {
  const {
    oxyServices,
    activeSessionId
  } = (0, _OxyContext.useOxy)();
  const queryClient = (0, _reactQuery.useQueryClient)();
  return (0, _reactQuery.useMutation)({
    mutationFn: async settings => {
      return await oxyServices.updateProfile({
        privacySettings: settings
      });
    },
    onMutate: async settings => {
      await queryClient.cancelQueries({
        queryKey: _queryKeys.queryKeys.accounts.settings()
      });
      const previousUser = queryClient.getQueryData(_queryKeys.queryKeys.accounts.current());
      if (previousUser) {
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), {
          ...previousUser,
          privacySettings: {
            ...previousUser.privacySettings,
            ...settings
          }
        });
      }
      return {
        previousUser
      };
    },
    onError: (error, settings, context) => {
      if (context?.previousUser) {
        queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), context.previousUser);
      }
      _sonner.toast.error(error instanceof Error ? error.message : 'Failed to update settings');
    },
    onSuccess: data => {
      queryClient.setQueryData(_queryKeys.queryKeys.accounts.current(), data);
      (0, _queryKeys.invalidateAccountQueries)(queryClient);
      _sonner.toast.success('Settings updated successfully');
    },
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: _queryKeys.queryKeys.accounts.settings()
      });
    }
  });
};
exports.useUpdateAccountSettings = useUpdateAccountSettings;
//# sourceMappingURL=useAccountMutations.js.map