/* SkyOps — Tenant scoping. Switching tenant reloads the app with SITES / INSPECTIONS / work orders / claims
   filtered to that tenant's sites. Hidden records are kept and merged back when stores persist. */

const TN_LIST = [
  { name: "Iberdrola Renovables", type: "owner", match: (s) => !/Solaria/.test(window.cmClient ? window.cmClient(s) : "") },
  { name: "Solaria Energía", type: "owner", match: (s) => /Solaria/.test(window.cmClient ? window.cmClient(s) : "") },
  { name: "AeroScan Ibérica", type: "provider", match: () => true },
  { name: "SkyOps demo tenant", type: "both", match: () => true, sandbox: true },
];
const skyTenant = () => localStorage.getItem("skyops_tenant") || TN_LIST[0].name;
const tnCur = () => TN_LIST.find(t => t.name === skyTenant()) || TN_LIST[0];

(function tnApply() {
  window.ALL_SITES = window.ALL_SITES || [...(window.SITES || [])];
  window.ALL_INSPECTIONS = window.ALL_INSPECTIONS || [...(window.INSPECTIONS || [])];
  const t = tnCur();
  const keep = new Set(window.ALL_SITES.filter(t.match).map(s => s.id));
  const scope = (arr, all, key) => { if (!arr) return; const v = all.filter(x => keep.has(x[key])); arr.length = 0; arr.push(...v); };
  scope(window.SITES, window.ALL_SITES, "id");
  scope(window.INSPECTIONS, window.ALL_INSPECTIONS, "siteId");
  const wrap = (store, key) => {
    if (!store || store.__tn) return; store.__tn = true;
    const hidden = store[key].filter(x => x.siteId && !keep.has(x.siteId));
    store[key] = store[key].filter(x => !x.siteId || keep.has(x.siteId));
    const orig = store.set.bind(store), vis = (x) => !x.siteId || keep.has(x.siteId);
    store.set = (fn) => { orig((l) => [...fn(l.filter(vis)), ...hidden]); store[key] = store[key].filter(vis); store.subs && store.subs.forEach(s => s(store[key])); };
  };
  wrap(window.woStore, "list");
  wrap(window.wcStore, "list");
  if (!window.SITES.some(s => s.id === localStorage.getItem("skyops_site")) && window.SITES[0]) localStorage.setItem("skyops_site", window.SITES[0].id);
})();

function tnSwitch(name) {
  if (name === skyTenant()) return;
  localStorage.setItem("skyops_tenant", name);
  localStorage.setItem("skyops_route", "portfolio");
  location.reload();
}
const tnSummary = (t) => { const ss = (window.ALL_SITES || []).filter(t.match); return t.sandbox ? "sandbox · sample data" : `${ss.length} site${ss.length === 1 ? "" : "s"} · ${Math.round(ss.reduce((a, s) => a + (s.capacity_mw || 0), 0))} MWp`; };

Object.assign(window, { TN_LIST, skyTenant, tnSwitch, tnSummary, tnCur });
