import AsyncStorage from "@react-native-async-storage/async-storage";

export const DEFAULT_URL = "https://gtd.rehbock.xyz/api";

let cached: { url: string; token: string } | null = null;

export async function getConfig() {
  if (!cached) {
    const [url, token] = await Promise.all([
      AsyncStorage.getItem("api_url"),
      AsyncStorage.getItem("api_token"),
    ]);
    cached = { url: url || DEFAULT_URL, token: token || "" };
  }
  return cached;
}

export async function setConfig(url: string, token: string) {
  cached = { url: url.trim().replace(/\/$/, "") || DEFAULT_URL, token: token.trim() };
  await Promise.all([
    AsyncStorage.setItem("api_url", cached.url),
    AsyncStorage.setItem("api_token", cached.token),
  ]);
}
