// src/components/Auth/useUrlAuthentication.ts
import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
var getAuthParams = (location, extractParams) => {
  const searchParams = new URLSearchParams(location.search);
  return extractParams ? extractParams(searchParams) : {
    sessionId: searchParams.get("sessionId"),
    token: searchParams.get("token"),
    refreshToken: searchParams.get("refreshToken")
  };
};
var hasValidAuthParams = (authParams) => {
  return !!(authParams?.sessionId && authParams?.token && authParams?.refreshToken);
};
var hasValidProfileData = (data) => {
  return data !== null && typeof data === "object" && data !== void 0;
};
var handleProfileSelection = (responseData, setSelectedProfile) => {
  if (!setSelectedProfile) return;
  if (!hasValidProfileData(responseData)) return;
  const profileId = responseData.profileId;
  const isValidProfileId = profileId !== null && profileId !== void 0;
  if (isValidProfileId) {
    setSelectedProfile({
      id: profileId
    });
  }
};
var handleUserData = (responseData, setUser) => {
  if (!setUser) return;
  if (!hasValidProfileData(responseData)) return;
  const userId = responseData.userId;
  const userName = responseData.userName;
  const userEmail = responseData.userEmail;
  if (userId) {
    const userData = {
      id: userId
    };
    if (userName) {
      userData.name = userName;
    }
    if (userEmail) {
      userData.email = userEmail;
    }
    setUser(userData);
  }
};
function useUrlAuthentication(options) {
  const location = useLocation();
  const processedRef = useRef(false);
  useEffect(() => {
    const handleAuthentication = async () => {
      if (processedRef.current) {
        return;
      }
      const authParams = getAuthParams(location, options.extractParams);
      if (!hasValidAuthParams(authParams)) {
        return;
      }
      processedRef.current = true;
      try {
        options.setTokens({
          token: authParams.token,
          refreshToken: authParams.refreshToken
        });
        const maxRetries = options.maxRetries || 3;
        const retryDelay = options.retryDelay || 1e3;
        let retries = 0;
        let sessionData = null;
        while (retries < maxRetries && !sessionData) {
          try {
            const response = await options.api.get(options.endpoint, {
              headers: {
                Authorization: `Bearer ${authParams.token}`
              }
            });
            sessionData = response.data.data;
            break;
          } catch (error) {
            retries++;
            console.warn(
              `Tentativa ${retries}/${maxRetries} falhou para ${options.endpoint}:`,
              error
            );
            if (retries < maxRetries) {
              await new Promise(
                (resolve) => setTimeout(resolve, retryDelay * retries)
              );
            } else {
              throw error;
            }
          }
        }
        options.setSessionInfo(sessionData);
        handleProfileSelection(sessionData, options.setSelectedProfile);
        handleUserData(sessionData, options.setUser);
        if (options.onAuthHydrated) await options.onAuthHydrated();
        options.clearParamsFromURL?.();
      } catch (error) {
        console.error("Erro ao obter informa\xE7\xF5es da sess\xE3o:", error);
        processedRef.current = false;
        options.onError?.(error);
      }
    };
    handleAuthentication();
  }, [
    location.search,
    options.setSessionInfo,
    options.setSelectedProfile,
    options.setUser,
    options.setTokens,
    options.api,
    options.endpoint,
    options.extractParams,
    options.clearParamsFromURL,
    options.maxRetries,
    options.retryDelay,
    options.onError,
    options.onAuthHydrated
  ]);
}
export {
  useUrlAuthentication
};
//# sourceMappingURL=index.mjs.map