import sql from 'mssql';
import { xmlTag, xmlElement } from './xml.js';

// PicklistenAusliefernOptionen.VersandSetzen (0x0002). DeliveryStep.Run always sets
// AuslieferungAusliefernContext.Optionen.VersandSetzen = true for POS/API orders
// (decompiled jtlCore.Classes.Sync.PosOrderSteps.DeliveryStep.cs:213), so we do too
// -- see delivery.md §0.1 for the cross-check that settled this.
const AUSLIEFERN_OPTIONS = 0x002;

/**
 * Actually delivers the session's committed Picklisten: creates the properly
 * numbered dbo.tLieferschein/tLieferscheinPos rows, links them back onto
 * tPicklistePos, decrements real warehouse stock (dbo.spWarenlagerAusgangSchreiben),
 * and bumps tPicklistePos.nStatus to 40. Mirrors
 * AuslieferungAusliefernContext.Commit -> Auslieferung.spPicklistenAusliefern.
 *
 * @Pakete matters even for local (non-fulfillment) warehouses: the nested
 * Auslieferung.spPicklistenAusliefern_PaketeErzeugen only creates a
 * dbo.tVersand row for a Lieferschein if #XMLPAKET (built straight from
 * @Pakete) contains at least one row for its kBestellung - if @Pakete is
 * NULL, #XMLPAKET stays empty and NO tVersand row is written for ANY
 * Lieferschein in the session, at all. So we always pass one <Paket> per
 * order carrying its kVersandArt (e.g. "Selbstabholer"), even though we
 * don't have real tracking/weight info to report yet.
 *
 * Returns the raw @xResult XML (NewDeliveryNotes/ProcessedPicklisten/... - see
 * delivery.md §3.3), read back via SELECT since tedious does not reliably
 * round-trip xml OUTPUT params for this proc.
 */
export async function deliverPicklists(transaction, kBenutzer, kSessionId, kAuftrag, kVersandArt) {
  const pakete = xmlElement('Paket', [
    xmlTag('kBestellung', kAuftrag),
    xmlTag('kVersandart', kVersandArt),
    xmlTag('fGewicht', 0), // NOT NULL column; real weight is recomputed from the order's articles further below in the proc
  ]);

  const result = await new sql.Request(transaction)
    .input('Pakete', sql.NVarChar(sql.MAX), pakete)
    .input('nOptions', sql.Int, AUSLIEFERN_OPTIONS)
    .input('kBenutzer', sql.Int, kBenutzer)
    .input('kSessionId', sql.Int, kSessionId)
    .query(`
      DECLARE @xHinweise XML = NULL;
      DECLARE @xPakete XML = CONVERT(XML, @Pakete);
      DECLARE @xResult XML;
      EXEC Auslieferung.spPicklistenAusliefern
        @xHinweise  = @xHinweise,
        @Pakete     = @xPakete,
        @nOptions   = @nOptions,
        @kBenutzer  = @kBenutzer,
        @kSessionId = @kSessionId,
        @xResult    = @xResult OUTPUT;
      SELECT @xResult AS xResult;
    `);
  return result.recordset[0]?.xResult ?? null;
}
