/**
 * Account Service
 * Verwaltet den aktiven Account über localStorage
 */

const ACTIVE_ACCOUNT_ID_KEY = "active_account_id";

/**
 * Gibt die ID des aktiven Accounts aus localStorage zurück
 * @returns {string|null} Account ID oder null
 */
export function getActiveAccountId() {
  try {
    return localStorage.getItem(ACTIVE_ACCOUNT_ID_KEY);
  } catch (e) {
    console.warn("Fehler beim Lesen von localStorage:", e);
    return null;
  }
}

/**
 * Speichert die ID des aktiven Accounts in localStorage
 * Dispatch ein CustomEvent für sofortigen Sidebar-Refresh
 * @param {string} accountId - Account ID
 */
export function setActiveAccountId(accountId) {
  try {
    if (accountId) {
      localStorage.setItem(ACTIVE_ACCOUNT_ID_KEY, accountId);
    } else {
      localStorage.removeItem(ACTIVE_ACCOUNT_ID_KEY);
    }
    
    // CustomEvent dispatch für Sidebar-Refresh
    window.dispatchEvent(
      new CustomEvent("activeAccountChanged", { detail: { accountId } })
    );
  } catch (e) {
    console.warn("Fehler beim Schreiben in localStorage:", e);
  }
}

/**
 * Bestimmt den aktiven Account aus der Liste
 * Wenn eine ID in localStorage gespeichert ist und gültig, wird dieser verwendet
 * Ansonsten wird der erste Account als Default genommen
 * @param {Array} accounts - Liste der Accounts
 * @returns {Object|null} Aktiver Account oder null
 */
export function resolveActiveAccount(accounts) {
  if (!accounts || accounts.length === 0) {
    return null;
  }

  const storedId = getActiveAccountId();
  
  if (storedId) {
    const foundAccount = accounts.find((acc) => acc.$id === storedId || acc.id === storedId);
    if (foundAccount) {
      return foundAccount;
    }
  }

  // Fallback: Erster Account als Default
  const firstAccount = accounts[0];
  if (firstAccount) {
    const accountId = firstAccount.$id || firstAccount.id;
    if (accountId) {
      setActiveAccountId(accountId);
    }
  }

  return firstAccount || null;
}

/**
 * Gibt den Display-Namen eines Accounts zurück
 * Priorität: account_shop_name > account_platform_account_id
 * @param {Object} account - Account Objekt
 * @returns {string} Display-Name
 */
export function getAccountDisplayName(account) {
  if (!account) return "";

  if (account.account_shop_name) {
    return account.account_shop_name;
  }

  if (account.account_platform_account_id) {
    return account.account_platform_account_id;
  }

  // Fallback für alte Datenstruktur
  if (account.shop) {
    return account.shop;
  }

  return account.id || account.$id || "Unknown Account";
}