import * as SecureStore from 'expo-secure-store';

const TOKEN_KEY = 'fedeo.mobile.auth.token';

let memoryToken: string | null = null;

async function hasSecureStore(): Promise<boolean> {
  try {
    return await SecureStore.isAvailableAsync();
  } catch {
    return false;
  }
}

export async function getStoredToken(): Promise<string | null> {
  if (await hasSecureStore()) {
    const token = await SecureStore.getItemAsync(TOKEN_KEY);
    memoryToken = token;
    return token;
  }

  return memoryToken;
}

export async function setStoredToken(token: string): Promise<void> {
  memoryToken = token;

  if (await hasSecureStore()) {
    await SecureStore.setItemAsync(TOKEN_KEY, token);
  }
}

export async function clearStoredToken(): Promise<void> {
  memoryToken = null;

  if (await hasSecureStore()) {
    await SecureStore.deleteItemAsync(TOKEN_KEY);
  }
}

export const tokenStorageInfo = {
  mode: 'secure-store',
  key: TOKEN_KEY,
} as const;
