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

const TOKEN_KEY = 'fedeo.mobile.auth.token';
const REFRESH_TOKEN_KEY = 'fedeo.mobile.auth.refresh-token';

let memoryToken: string | null = null;
let memoryRefreshToken: string | null = null;

export type StoredSession = {
  token: string;
  refreshToken: string;
};

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 getStoredSession(): Promise<StoredSession | null> {
  if (await hasSecureStore()) {
    const [token, refreshToken] = await Promise.all([
      SecureStore.getItemAsync(TOKEN_KEY),
      SecureStore.getItemAsync(REFRESH_TOKEN_KEY),
    ]);
    memoryToken = token;
    memoryRefreshToken = refreshToken;
  }

  if (!memoryToken || !memoryRefreshToken) return null;
  return { token: memoryToken, refreshToken: memoryRefreshToken };
}

export async function setStoredSession(session: StoredSession): Promise<void> {
  memoryToken = session.token;
  memoryRefreshToken = session.refreshToken;

  if (await hasSecureStore()) {
    await Promise.all([
      SecureStore.setItemAsync(TOKEN_KEY, session.token),
      SecureStore.setItemAsync(REFRESH_TOKEN_KEY, session.refreshToken),
    ]);
  }
}

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

  if (await hasSecureStore()) {
    await Promise.all([
      SecureStore.deleteItemAsync(TOKEN_KEY),
      SecureStore.deleteItemAsync(REFRESH_TOKEN_KEY),
    ]);
  }
}

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