// Use a single canonical key for the auth token across the app
// Many modules expect 'auth_token' (see usages in services and build artifacts).
const TOKEN_KEY = 'auth_token';
const HAS_ADMIN_KEY = 'fotbal_club_has_admin';

export const getToken = (): string | null => {
  // Read from localStorage first (remembered), then fall back to sessionStorage
  // Keep backward compatibility with code that may still use sessionStorage.
  try {
    return localStorage.getItem(TOKEN_KEY) ?? sessionStorage.getItem(TOKEN_KEY);
  } catch {
    return null;
  }
};

export const setToken = (token: string, remember = true): void => {
  // Clear both first to avoid duplicates
  try { localStorage.removeItem(TOKEN_KEY); } catch {}
  try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
  if (remember) {
    try { localStorage.setItem(TOKEN_KEY, token); } catch {}
  } else {
    try { sessionStorage.setItem(TOKEN_KEY, token); } catch {}
  }
};

export const clearToken = (): void => {
  try { localStorage.removeItem(TOKEN_KEY); } catch {}
  try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
};

export const isAuthenticated = (): boolean => {
  return !!getToken();
};

export const hasAdmin = (): boolean => {
  return localStorage.getItem(HAS_ADMIN_KEY) === 'true';
};

export const setHasAdmin = (value: boolean): void => {
  localStorage.setItem(HAS_ADMIN_KEY, String(value));
};

export const checkAdminExists = async (): Promise<boolean> => {
  try {
    const base = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
    const response = await fetch(`${base}/auth/admin/exists`, {
      headers: { 'Accept': 'application/json' },
    });
    if (response.ok) {
      const data = await response.json();
      const exists = Boolean((data && (data.hasAdmin ?? data.has_admin)));
      setHasAdmin(exists);
      return exists;
    }
    return false;
  } catch (error) {
    console.error('Error checking admin status:', error);
    return false;
  }
};
