-- Auszahlungskonto (Bankkarte des Kunden) fuer Geld-Gutschriften.
-- ON DELETE SET NULL: Loeschen der Bankkarte reisst die Gutschrift nicht mit.
ALTER TABLE `CreditNote` ADD COLUMN IF NOT EXISTS `payoutBankCardId` INT NULL;

-- FK nur anlegen, wenn noch nicht vorhanden (idempotent via information_schema).
SET @fk := (SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
  WHERE CONSTRAINT_SCHEMA = DATABASE() AND TABLE_NAME = 'CreditNote'
  AND CONSTRAINT_NAME = 'CreditNote_payoutBankCardId_fkey');
SET @sql := IF(@fk = 0,
  'ALTER TABLE `CreditNote` ADD CONSTRAINT `CreditNote_payoutBankCardId_fkey` FOREIGN KEY (`payoutBankCardId`) REFERENCES `BankCard`(`id`) ON DELETE SET NULL ON UPDATE CASCADE',
  'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx := (SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'CreditNote'
  AND INDEX_NAME = 'CreditNote_payoutBankCardId_idx');
SET @sql2 := IF(@idx = 0,
  'CREATE INDEX `CreditNote_payoutBankCardId_idx` ON `CreditNote`(`payoutBankCardId`)',
  'SELECT 1');
PREPARE stmt2 FROM @sql2; EXECUTE stmt2; DEALLOCATE PREPARE stmt2;
