-- Gutschriften (Subventionen) zu einem Vertrag: Geldbetrag (Überweisung)
-- oder Sachwert. USt pro Gutschrift wählbar (vatRelevant + Basis Netto/Brutto).
-- ZUGFeRD-taugliches Datenmodell (Netto/USt/Brutto getrennt).
-- ON DELETE CASCADE: wird der Vertrag gelöscht, verschwinden die Gutschriften.

CREATE TABLE IF NOT EXISTS `CreditNote` (
  `id`                  INT NOT NULL AUTO_INCREMENT,
  `contractId`          INT NOT NULL,
  `number`              VARCHAR(191) NOT NULL,
  `type`                ENUM('GELD', 'SACHWERT') NOT NULL,
  `sachwertDescription` VARCHAR(191) NULL,
  `customerType`        ENUM('PRIVAT', 'FIRMA') NOT NULL,
  `vatRelevant`         BOOLEAN NOT NULL DEFAULT false,
  `amountBasis`         ENUM('NETTO', 'BRUTTO') NOT NULL DEFAULT 'BRUTTO',
  `vatRate`             DOUBLE NOT NULL DEFAULT 19,
  `amountNet`           DOUBLE NOT NULL DEFAULT 0,
  `amountVat`           DOUBLE NOT NULL DEFAULT 0,
  `amountGross`         DOUBLE NOT NULL DEFAULT 0,
  `currency`            VARCHAR(191) NOT NULL DEFAULT 'EUR',
  `creditDate`          DATETIME(3) NOT NULL,
  `place`               VARCHAR(191) NULL,
  `signedAt`            DATETIME(3) NULL,
  `goodsReceived`       BOOLEAN NOT NULL DEFAULT false,
  `receiptPath`         VARCHAR(191) NULL,
  `pdfPath`             VARCHAR(191) NULL,
  `notes`               TEXT NULL,
  `createdBy`           VARCHAR(191) NULL,
  `createdAt`           DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updatedAt`           DATETIME(3) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `CreditNote_number_key` (`number`),
  INDEX `CreditNote_contractId_idx` (`contractId`),
  CONSTRAINT `CreditNote_contractId_fkey` FOREIGN KEY (`contractId`)
    REFERENCES `Contract` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Nummernkreis (Einzel-Zeile, in den Einstellungen verwaltbar).
CREATE TABLE IF NOT EXISTS `CreditNoteNumberRange` (
  `id`          INT NOT NULL AUTO_INCREMENT,
  `prefix`      VARCHAR(191) NOT NULL DEFAULT 'GS-',
  `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;
