import sql from 'mssql';

/** DB-resolved (or env-overridden) outgoing warehouse, cached after first lookup. */
let cachedWarenLager = null;

/**
 * Resolves the local warehouse (dbo.tWarenLager.nFulfillment = 0) to book
 * stock out of. JTL's own PosWarehouseService.FindeWarenlagerFuerAusgang()
 * (jtlCore, obfuscated) is not yet decompiled/traced (see delivery.md §7), so
 * we approximate it: use JTL_KWARENLAGER if configured, otherwise pick the
 * highest-priority active local warehouse. This is correct for the common
 * single-warehouse setup; multi-warehouse setups should set JTL_KWARENLAGER
 * explicitly until FindeWarenlagerFuerAusgang() is fully traced.
 */
export async function getOutgoingWarehouse(transaction) {
  if (cachedWarenLager != null) {
    return cachedWarenLager;
  }

  const configured = Number(process.env.JTL_KWARENLAGER);
  if (Number.isInteger(configured) && configured > 0) {
    cachedWarenLager = configured;
    return cachedWarenLager;
  }

  const result = await new sql.Request(transaction).query(`
    SELECT TOP 1 kWarenLager
    FROM dbo.tWarenLager
    WHERE nFulfillment = 0 AND ISNULL(nAktiv, 1) = 1
    ORDER BY nAuslieferungsPrio, kWarenLager
  `);
  const row = result.recordset[0];
  if (!row) {
    throw new Error('No local warehouse (dbo.tWarenLager.nFulfillment = 0) found; set JTL_KWARENLAGER explicitly.');
  }
  cachedWarenLager = row.kWarenLager;
  return cachedWarenLager;
}
