import {
  GetAsyncStorageItemParams,
  SetAsyncStorageItemParams,
  RemoveAsyncStorageItemParams,
} from '@shopify/shop-minis-platform/actions'

import {useHandleAction} from '../../internal/useHandleAction'
import {useShopActions} from '../../internal/useShopActions'

interface UseAsyncStorageReturns {
  /**
   * Get an item from the async storage.
   */
  getItem: (params: GetAsyncStorageItemParams) => Promise<string | null>
  /**
   * Set an item in the async storage.
   */
  setItem: (params: SetAsyncStorageItemParams) => Promise<void>
  /**
   * Remove an item from the async storage.
   */
  removeItem: (params: RemoveAsyncStorageItemParams) => Promise<void>
  /**
   * Get all keys in the async storage.
   */
  getAllKeys: () => Promise<string[]>
  /**
   * Clear all items from the async storage.
   */
  clear: () => Promise<void>
}

export function useAsyncStorage(): UseAsyncStorageReturns {
  const {
    getPersistedItem,
    setPersistedItem,
    removePersistedItem,
    getAllPersistedKeys,
    clearPersistedItems,
  } = useShopActions()

  return {
    getItem: useHandleAction(getPersistedItem),
    setItem: useHandleAction(setPersistedItem),
    removeItem: useHandleAction(removePersistedItem),
    getAllKeys: useHandleAction(getAllPersistedKeys),
    clear: useHandleAction(clearPersistedItems),
  }
}
