"use client";

import { useCallback, useMemo } from "react";
import { useStorageService } from "./storage-provider";

export interface NamespacedStorage {
  get: <T>(key: string) => Promise<T | null>;
  set: <T>(key: string, value: T) => Promise<void>;
  delete: (key: string) => Promise<void>;
  list: () => Promise<string[]>;
  query: <T>(predicate: (item: T) => boolean) => Promise<T[]>;
  clear: () => Promise<void>;
  exportAll: (options?: {
    lightweight?: boolean;
  }) => Promise<Record<string, unknown>>;
  importAll: (data: Record<string, unknown>) => Promise<void>;
}

export function useStorage(namespace: string): NamespacedStorage {
  const service = useStorageService();

  const get = useCallback(
    <T>(key: string) => service.get<T>(namespace, key),
    [service, namespace],
  );

  const set = useCallback(
    <T>(key: string, value: T) => service.set<T>(namespace, key, value),
    [service, namespace],
  );

  const del = useCallback(
    (key: string) => service.delete(namespace, key),
    [service, namespace],
  );

  const list = useCallback(() => service.list(namespace), [service, namespace]);

  const query = useCallback(
    <T>(predicate: (item: T) => boolean) =>
      service.query<T>(namespace, predicate),
    [service, namespace],
  );

  const clear = useCallback(
    () => service.clear(namespace),
    [service, namespace],
  );

  const exportAll = useCallback(
    (options?: { lightweight?: boolean }) => service.export(namespace, options),
    [service, namespace],
  );

  const importAll = useCallback(
    (data: Record<string, unknown>) => service.import(namespace, data),
    [service, namespace],
  );

  return useMemo(
    () => ({ get, set, delete: del, list, query, clear, exportAll, importAll }),
    [get, set, del, list, query, clear, exportAll, importAll],
  );
}
