import sql from 'mssql';

/**
 * Opens a JTL "Auslieferung" session by inserting a row into dbo.tSessionId,
 * mirroring jtlCore.Classes.SessionManager.GetSessionId(). All of the
 * Auslieferung.sp* calls in this delivery/ folder are scoped to this
 * kSessionId (see ../../../delivery.md §2).
 */
export async function openSession(transaction, kBenutzer, hostname = 'jtlsrv') {
  const result = await new sql.Request(transaction)
    .input('cRechnername', sql.NVarChar(255), hostname)
    .input('kBenutzer', sql.Int, kBenutzer)
    .query(`
      DECLARE @t TABLE ([kSessionId] INT);
      INSERT INTO dbo.tSessionId (cRechnername, kBenutzer, dLastAction)
      OUTPUT inserted.kSessionId INTO @t
      VALUES (@cRechnername, @kBenutzer, DATEADD(day, 10, GETDATE()));
      SELECT kSessionId FROM @t;
    `);
  return result.recordset[0].kSessionId;
}

/**
 * Discards any reservation belonging to this session that never made it into
 * a delivered Pickliste. Auslieferung.spPicklistenVerwerfen only ever deletes
 * dbo.tPickliste rows with nStatus < 10 for this session, so it's safe (and
 * recommended, see delivery.md §0.1) to call this unconditionally, both after
 * a successful delivery and on the error path.
 */
export async function discardSession(transaction, kBenutzer, kSessionId) {
  await new sql.Request(transaction)
    .input('kBenutzer', sql.Int, kBenutzer)
    .input('kSessionId', sql.Int, kSessionId)
    .execute('Auslieferung.spPicklistenVerwerfen');
}

/**
 * Mirrors SessionManager.Dispose(): removes the housekeeping row from
 * dbo.tSessionId. Not strictly required for correctness (it only affects the
 * Wawi GUI's "who's editing what" bookkeeping), but keeps the table tidy.
 */
export async function closeSession(transaction, kSessionId) {
  await new sql.Request(transaction)
    .input('kSessionId', sql.Int, kSessionId)
    .query('DELETE FROM dbo.tSessionId WHERE kSessionId = @kSessionId');
}
