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

let inMemoryToken: string | null = null;

export const getToken = (): string | null => inMemoryToken;

export const setToken = async (token: string | null) => {
  inMemoryToken = token;
  try {
    if (Platform.OS === "web") {
      if (token) localStorage.setItem("auth_token", token);
      else localStorage.removeItem("auth_token");
    } else {
      if (token) await SecureStore.setItemAsync("auth_token", token);
      else await SecureStore.deleteItemAsync("auth_token");
    }
  } catch (e) {
    console.warn("Token persistence error:", e);
  }
};

export const loadPersistedToken = async (): Promise<string | null> => {
  try {
    if (Platform.OS === "web") {
      const t = localStorage.getItem("auth_token");
      inMemoryToken = t;
      return t;
    }
    const t = await SecureStore.getItemAsync("auth_token");
    inMemoryToken = t;
    return t;
  } catch (e) {
    console.warn("Token load error:", e);
    return null;
  }
};