import * as SecureStore from "expo-secure-store";
import { Platform } from "react-native";

interface Storage {
  getItem(key: string): Promise<string | null>;
  setItem(key: string, value: string): Promise<void>;
  removeItem(key: string): Promise<void>;
}

class WebStorage implements Storage {
  async getItem(key: string): Promise<string | null> {
    if (typeof window === "undefined") return null;
    return window.localStorage.getItem(key);
  }

  async setItem(key: string, value: string): Promise<void> {
    if (typeof window === "undefined") return;
    window.localStorage.setItem(key, value);
  }

  async removeItem(key: string): Promise<void> {
    if (typeof window === "undefined") return;
    console.log(`[WebStorage] Removing key: ${key}`);
    window.localStorage.removeItem(key);
    console.log(`[WebStorage] Key removed. Verification:`, window.localStorage.getItem(key));
  }
}

class NativeStorage implements Storage {
  async getItem(key: string): Promise<string | null> {
    return await SecureStore.getItemAsync(key);
  }

  async setItem(key: string, value: string): Promise<void> {
    await SecureStore.setItemAsync(key, value);
  }

  async removeItem(key: string): Promise<void> {
    console.log(`[NativeStorage] Removing key: ${key}`);
    await SecureStore.deleteItemAsync(key);
    console.log(`[NativeStorage] Key removed`);
  }
}

export const storage: Storage = Platform.OS === "web" ? new WebStorage() : new NativeStorage();
