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

import { DEFAULT_API_BASE_URL } from '@/src/config/env';

const SERVER_BASE_KEY = 'fedeo.mobile.server.base';
const SERVER_SETUP_DONE_KEY = 'fedeo.mobile.server.setup.done';

let memoryApiBaseUrl = DEFAULT_API_BASE_URL;
let memorySetupDone = false;

function normalizeApiBaseUrl(value: string): string {
  return value.trim().replace(/\/+$/, '');
}

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

export function getApiBaseUrlSync(): string {
  return memoryApiBaseUrl || DEFAULT_API_BASE_URL;
}

export async function hydrateApiBaseUrl(): Promise<string> {
  if (await hasSecureStore()) {
    const stored = await SecureStore.getItemAsync(SERVER_BASE_KEY);
    const setupDone = await SecureStore.getItemAsync(SERVER_SETUP_DONE_KEY);
    memorySetupDone = setupDone === '1';

    if (stored) {
      memoryApiBaseUrl = normalizeApiBaseUrl(stored);
      return memoryApiBaseUrl;
    }
  } else {
    memorySetupDone = false;
  }

  memoryApiBaseUrl = DEFAULT_API_BASE_URL;
  return memoryApiBaseUrl;
}

export async function isServerSetupDone(): Promise<boolean> {
  if (await hasSecureStore()) {
    const setupDone = await SecureStore.getItemAsync(SERVER_SETUP_DONE_KEY);
    memorySetupDone = setupDone === '1';
    return memorySetupDone;
  }

  return memorySetupDone;
}

export async function markServerSetupDone(): Promise<void> {
  memorySetupDone = true;

  if (await hasSecureStore()) {
    await SecureStore.setItemAsync(SERVER_SETUP_DONE_KEY, '1');
  }
}

export async function setApiBaseUrl(nextApiBaseUrl: string): Promise<string> {
  const normalized = normalizeApiBaseUrl(nextApiBaseUrl);
  memoryApiBaseUrl = normalized;

  if (await hasSecureStore()) {
    await SecureStore.setItemAsync(SERVER_BASE_KEY, normalized);
    await SecureStore.setItemAsync(SERVER_SETUP_DONE_KEY, '1');
  }
  memorySetupDone = true;

  return normalized;
}

export async function resetApiBaseUrl(): Promise<string> {
  memoryApiBaseUrl = DEFAULT_API_BASE_URL;

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

  return memoryApiBaseUrl;
}

export const serverStorageInfo = {
  mode: 'secure-store',
  key: SERVER_BASE_KEY,
  setupKey: SERVER_SETUP_DONE_KEY,
  fallback: DEFAULT_API_BASE_URL,
} as const;
