"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useUserDevices = exports.useSessions = exports.useSession = exports.useSecurityInfo = exports.useDeviceSessions = void 0;
var _reactQuery = require("@tanstack/react-query");
var _queryKeys = require("./queryKeys");
var _OxyContext = require("../../context/OxyContext");
var _sessionHelpers = require("../../context/utils/sessionHelpers");
/**
 * Get all active sessions for the current user
 */
const useSessions = (userId, options) => {
  const {
    oxyServices,
    activeSessionId
  } = (0, _OxyContext.useOxy)();
  return (0, _reactQuery.useQuery)({
    queryKey: _queryKeys.queryKeys.sessions.list(userId),
    queryFn: async () => {
      if (!activeSessionId) {
        throw new Error('No active session');
      }
      const sessions = await (0, _sessionHelpers.fetchSessionsWithFallback)(oxyServices, activeSessionId, {
        fallbackDeviceId: undefined,
        fallbackUserId: userId
      });
      return (0, _sessionHelpers.mapSessionsToClient)(sessions, activeSessionId);
    },
    enabled: options?.enabled !== false && !!activeSessionId,
    staleTime: 2 * 60 * 1000,
    // 2 minutes (sessions change frequently)
    gcTime: 10 * 60 * 1000 // 10 minutes
  });
};

/**
 * Get specific session by ID
 */
exports.useSessions = useSessions;
const useSession = (sessionId, options) => {
  const {
    oxyServices
  } = (0, _OxyContext.useOxy)();
  return (0, _reactQuery.useQuery)({
    queryKey: _queryKeys.queryKeys.sessions.detail(sessionId || ''),
    queryFn: async () => {
      if (!sessionId) {
        throw new Error('Session ID is required');
      }
      const validation = await oxyServices.validateSession(sessionId, {
        useHeaderValidation: true
      });
      if (!validation?.valid || !validation.user) {
        throw new Error('Session not found or invalid');
      }
      const now = new Date();
      return {
        sessionId,
        deviceId: '',
        // Device ID not available from validation response
        expiresAt: validation.expiresAt || new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(),
        lastActive: validation.lastActivity || now.toISOString(),
        userId: validation.user.id?.toString() ?? '',
        isCurrent: false
      };
    },
    enabled: options?.enabled !== false && !!sessionId,
    staleTime: 2 * 60 * 1000,
    gcTime: 10 * 60 * 1000
  });
};

/**
 * Get device sessions for the current active session
 */
exports.useSession = useSession;
const useDeviceSessions = options => {
  const {
    oxyServices,
    activeSessionId
  } = (0, _OxyContext.useOxy)();
  return (0, _reactQuery.useQuery)({
    queryKey: _queryKeys.queryKeys.sessions.active(),
    queryFn: async () => {
      if (!activeSessionId) {
        throw new Error('No active session');
      }
      return await oxyServices.getDeviceSessions(activeSessionId);
    },
    enabled: options?.enabled !== false && !!activeSessionId,
    staleTime: 2 * 60 * 1000,
    gcTime: 10 * 60 * 1000
  });
};

/**
 * Get user devices
 */
exports.useDeviceSessions = useDeviceSessions;
const useUserDevices = options => {
  const {
    oxyServices,
    isAuthenticated,
    activeSessionId,
    syncIdentity
  } = (0, _OxyContext.useOxy)();
  return (0, _reactQuery.useQuery)({
    queryKey: _queryKeys.queryKeys.devices.list(),
    queryFn: async () => {
      // 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.getUserDevices();
      } 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 request after getting token
              return await oxyServices.getUserDevices();
            } 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;
      }
    },
    enabled: options?.enabled !== false && isAuthenticated,
    staleTime: 5 * 60 * 1000,
    gcTime: 30 * 60 * 1000
  });
};

/**
 * Get security information
 */
exports.useUserDevices = useUserDevices;
const useSecurityInfo = options => {
  const {
    oxyServices,
    isAuthenticated
  } = (0, _OxyContext.useOxy)();
  return (0, _reactQuery.useQuery)({
    queryKey: [..._queryKeys.queryKeys.devices.all, 'security'],
    queryFn: async () => {
      return await oxyServices.getSecurityInfo();
    },
    enabled: options?.enabled !== false && isAuthenticated,
    staleTime: 5 * 60 * 1000,
    gcTime: 30 * 60 * 1000
  });
};
exports.useSecurityInfo = useSecurityInfo;
//# sourceMappingURL=useServicesQueries.js.map