// Pure host → Biatec-project matcher shared by BC's main-process handlers.
//
// Matches by EXACT host equality (scheme-aware), with a scheme-less substring
// fallback for legacy `eshop_url` rows stored without "https://". There is
// deliberately NO `|| projects[0]` fallback: an unrecognised host returns null
// so every caller fails closed.
//
// Why this matters (QA bug 2026-07-02, multi-tenant data isolation): the old
// `projects.find(p => p.eshop_url.indexOf(host) !== -1) || projects[0]` pattern
// silently attributed an order to the FIRST project in the list whenever the
// host match missed — so a shipment created while viewing e-shop A could be
// filed under e-shop B (another store / Project ID). The BE trusts the
// client-supplied projectId under admin (Bearer) auth, so a wrong projectId
// here lands real order data in the wrong e-shop. Fail closed instead.
(function (root) {
  function hostOf(u) {
    try { return new URL(u).host.replace(/^www\./, '').toLowerCase(); }
    catch (e) { return ''; }
  }

  // Returns the single project whose eshop_url host equals `url`'s host, or null.
  function findProjectByHost(projects, url) {
    if (!Array.isArray(projects)) return null;
    var host = hostOf(url);
    if (!host) return null;
    return projects.find(function (p) {
      if (!p || !p.eshop_url) return false;
      var eh = hostOf(p.eshop_url);
      if (eh) return eh === host;
      // Legacy row stored without a scheme → best-effort substring match.
      return p.eshop_url.toLowerCase().indexOf(host) !== -1;
    }) || null;
  }

  var api = { findProjectByHost: findProjectByHost, hostOf: hostOf };
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
  else { root.NP = root.NP || {}; root.NP.projectMatch = api; }
})(typeof self !== 'undefined' ? self : this);
