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

export const MOBILE_SESSION_STORAGE_KEY = 'invttrdg-auth';

async function getFallbackValue(key: string) {
  return AsyncStorage.getItem(key);
}

export const secureSessionStorage = {
  async getItem(key: string) {
    try {
      const value = await SecureStore.getItemAsync(key);
      if (value != null) {
        return value;
      }
    } catch {
      // Fall back when SecureStore is unavailable in the current runtime.
    }

    return getFallbackValue(key);
  },

  async setItem(key: string, value: string) {
    try {
      await SecureStore.setItemAsync(key, value);
      await AsyncStorage.removeItem(key);
      return;
    } catch {
      await AsyncStorage.setItem(key, value);
    }
  },

  async removeItem(key: string) {
    await Promise.allSettled([
      SecureStore.deleteItemAsync(key),
      AsyncStorage.removeItem(key),
    ]);
  },
};

export async function clearMobileSessionStorage() {
  await secureSessionStorage.removeItem(MOBILE_SESSION_STORAGE_KEY);
}
