import AsyncStorage from '@react-native-async-storage/async-storage';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';

/**
 * Cross-platform storage utility that works on both web and native platforms.
 * Uses SecureStore on native platforms and AsyncStorage on web.
 */
export const Storage = {
  /**
   * Store a value securely
   */
  setItem: async (key: string, value: string): Promise<void> => {
    try {
      if (Platform.OS === 'web') {
        await AsyncStorage.setItem(key, value);
      } else {
        await SecureStore.setItemAsync(key, value);
      }
    } catch (error) {
      console.error('Error storing value:', error);
    }
  },

  /**
   * Retrieve a stored value
   */
  getItem: async (key: string): Promise<string | null> => {
    try {
      if (Platform.OS === 'web') {
        return await AsyncStorage.getItem(key);
      } else {
        return await SecureStore.getItemAsync(key);
      }
    } catch (error) {
      console.error('Error retrieving value:', error);
      return null;
    }
  },

  /**
   * Delete a stored value
   */
  deleteItem: async (key: string): Promise<void> => {
    try {
      if (Platform.OS === 'web') {
        await AsyncStorage.removeItem(key);
      } else {
        await SecureStore.deleteItemAsync(key);
      }
    } catch (error) {
      console.error('Error deleting value:', error);
    }
  },

  /**
   * Check if a key exists in storage
   */
  hasItem: async (key: string): Promise<boolean> => {
    try {
      const value = await Storage.getItem(key);
      return value !== null;
    } catch (error) {
      console.error('Error checking for key:', error);
      return false;
    }
  }
};
