// lib/company.ts
export async function fetchAndSetCompanyFromMe() {
  try {
    const res = await fetch("/api/me", { cache: "no-store" });
    if (!res.ok) return false;
    const me = await res.json();

    const name = me?.active_org_name?.trim() || null;
    const apiName = me?.active_org_api_name?.trim() || me?.structure_api?.trim() || null;
    const b64 = name ? btoa(unescape(encodeURIComponent(name))) : null;

    if (name) localStorage.setItem("company_name", name); else localStorage.removeItem("company_name");
    if (apiName) localStorage.setItem("company_api_name", apiName); else localStorage.removeItem("company_api_name");
    if (b64) localStorage.setItem("x-company-name-b64", b64); else localStorage.removeItem("x-company-name-b64");

    return true;
  } catch {
    return false;
  }
}