"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useStorage = void 0;
var _react = require("react");
var _storageHelpers = require("../utils/storageHelpers");
var _errorHandlers = require("../utils/errorHandlers");
const DEFAULT_ERROR_CODE = 'STORAGE_INIT_ERROR';

/**
 * React hook that exposes a platform-agnostic storage reference.
 * Handles initialization, error propagation, and lazy re-initialization.
 *
 * @param options - Optional configuration for error reporting and logging
 */
const useStorage = ({
  onError,
  logger,
  errorCode = DEFAULT_ERROR_CODE
} = {}) => {
  const [storage, setStorage] = (0, _react.useState)(null);
  const [error, setError] = (0, _react.useState)(null);
  const initializingRef = (0, _react.useRef)(null);
  const notifyError = (0, _react.useCallback)(err => {
    const message = (0, _errorHandlers.extractErrorMessage)(err, 'Failed to initialize storage');
    setError(message);
    if (logger) {
      logger(message, err);
    }
    onError?.({
      message,
      code: errorCode,
      status: 500
    });
  }, [errorCode, logger, onError]);
  const createStorageInstance = (0, _react.useCallback)(async () => {
    try {
      const platformStorage = await (0, _storageHelpers.createPlatformStorage)();
      setStorage(platformStorage);
      setError(null);
      return platformStorage;
    } catch (err) {
      notifyError(err);
      setStorage(null);
      return null;
    }
  }, [notifyError]);
  const refresh = (0, _react.useCallback)(async () => {
    if (!initializingRef.current) {
      initializingRef.current = createStorageInstance().finally(() => {
        initializingRef.current = null;
      });
    }
    return initializingRef.current;
  }, [createStorageInstance]);
  (0, _react.useEffect)(() => {
    refresh().catch(err => {
      notifyError(err);
    });
  }, [refresh, notifyError]);
  const withStorage = (0, _react.useCallback)(async callback => {
    const resolvedStorage = storage ?? (await refresh());
    if (!resolvedStorage) {
      return null;
    }
    return callback(resolvedStorage);
  }, [refresh, storage]);
  return {
    storage,
    isReady: Boolean(storage) && !error,
    error,
    refresh,
    withStorage
  };
};
exports.useStorage = useStorage;
//# sourceMappingURL=useStorage.js.map