-- Lieferschein-Nummerierung fuer betragslose Sachwert-Uebergaben:
-- eigene Nummer am Beleg + eigener Nummernkreis (getrennt von Gutschriften).

ALTER TABLE `CreditNote` ADD COLUMN IF NOT EXISTS `deliveryNoteNumber` VARCHAR(191) NULL;

-- UNIQUE-Index auf deliveryNoteNumber (idempotent).
SET @idx := (SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'CreditNote'
  AND INDEX_NAME = 'CreditNote_deliveryNoteNumber_key');
SET @sql := IF(@idx = 0,
  'CREATE UNIQUE INDEX `CreditNote_deliveryNoteNumber_key` ON `CreditNote`(`deliveryNoteNumber`)',
  'SELECT 1');
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;

CREATE TABLE IF NOT EXISTS `DeliveryNoteNumberRange` (
  `id`          INT NOT NULL AUTO_INCREMENT,
  `prefix`      VARCHAR(191) NOT NULL DEFAULT 'LS-',
  `includeYear` BOOLEAN NOT NULL DEFAULT true,
  `separator`   VARCHAR(191) NOT NULL DEFAULT '-',
  `padding`     INT NOT NULL DEFAULT 4,
  `nextNumber`  INT NOT NULL DEFAULT 1,
  `resetYearly` BOOLEAN NOT NULL DEFAULT true,
  `currentYear` INT NULL,
  `updatedAt`   DATETIME(3) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
