"use client";

import { createContext, useContext, useMemo } from "react";
import type { StorageService } from "./types";
import { LocalStorageAdapter } from "./adapters/local-storage";
import { DatabaseStorageAdapter } from "./adapters/database-adapter";

const StorageContext = createContext<StorageService | null>(null);

function createAdapter(): StorageService {
  const adapterType = process.env.NEXT_PUBLIC_STORAGE_ADAPTER;

  if (adapterType === "database") {
    return new DatabaseStorageAdapter();
  }

  return new LocalStorageAdapter();
}

interface StorageProviderProps {
  children: React.ReactNode;
}

export function StorageProvider({ children }: StorageProviderProps) {
  const service = useMemo(() => createAdapter(), []);

  return (
    <StorageContext.Provider value={service}>
      {children}
    </StorageContext.Provider>
  );
}

export function useStorageService(): StorageService {
  const ctx = useContext(StorageContext);
  if (!ctx)
    throw new Error("useStorageService must be used within StorageProvider");
  return ctx;
}
