-- ============================================================
-- Postprocessing Redesign Migration
-- Ausführen: mysql -h HOST -u USER -p DATABASE < migration.sql
-- ============================================================

-- 1) Postprocessings: Statische Filter → JSON
ALTER TABLE Postprocessings ADD COLUMN FilterJson JSON NOT NULL DEFAULT (JSON_OBJECT('combinator', 'AND', 'rules', JSON_ARRAY()));
ALTER TABLE Postprocessings DROP COLUMN IF EXISTS DocumentTypeId;
ALTER TABLE Postprocessings DROP COLUMN IF EXISTS CorrespondentId;
ALTER TABLE Postprocessings DROP COLUMN IF EXISTS OwnerId;
ALTER TABLE Postprocessings DROP COLUMN IF EXISTS TagId;
ALTER TABLE Postprocessings DROP COLUMN IF EXISTS MandantId;

-- 2) PostprocessingActions: Content text → JSON
ALTER TABLE PostprocessingActions MODIFY COLUMN Content JSON NOT NULL;

-- 3) ExportTargets (NEU)
CREATE TABLE IF NOT EXISTS ExportTargets (
  Id INT AUTO_INCREMENT PRIMARY KEY,
  Name VARCHAR(100) NOT NULL,
  Protocol VARCHAR(20) NOT NULL COMMENT 'ftp | webdav',
  Host VARCHAR(255) NOT NULL,
  Port INT NULL,
  Username VARCHAR(100) NULL,
  Password VARCHAR(255) NULL,
  RemotePath VARCHAR(500) NULL,
  IsActive TINYINT NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 4) PostprocessingLogs (NEU)
CREATE TABLE IF NOT EXISTS PostprocessingLogs (
  Id INT AUTO_INCREMENT PRIMARY KEY,
  PostprocessingId INT NOT NULL,
  ActionId INT NULL,
  DocumentId INT NOT NULL,
  Status VARCHAR(20) NOT NULL COMMENT 'success | error | skipped',
  Message TEXT NULL,
  CreatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_pp_doc (PostprocessingId, DocumentId),
  INDEX idx_created (CreatedAt)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
