-- Migration 050: Medien-Volljournal – Audit-Log für alle Änderungen + Korrektur-Deklarationen

-- Vollständiger Audit-Log: Sichtbarkeitsänderungen, Copyright, Metadaten, Lifecycle
CREATE TABLE IF NOT EXISTS media_asset_audit_log (
    id                  SERIAL PRIMARY KEY,
    media_asset_id      INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
    acting_profile_id   INT REFERENCES profiles(id) ON DELETE SET NULL,
    occurred_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    event_type          VARCHAR(50) NOT NULL
        CHECK (event_type IN (
            'visibility_change',
            'copyright_change',
            'metadata_change',
            'lifecycle_change'
        )),
    old_values          JSONB,
    new_values          JSONB
);

CREATE INDEX IF NOT EXISTS idx_maal_asset ON media_asset_audit_log (media_asset_id);
CREATE INDEX IF NOT EXISTS idx_maal_asset_occurred ON media_asset_audit_log (media_asset_id, occurred_at);

COMMENT ON TABLE media_asset_audit_log IS
    'Append-only Protokoll aller Aenderungen an Medien-Assets (Sichtbarkeit, Copyright, Metadaten, Lifecycle). '
    'Wird nie aktualisiert oder geloescht (ausser ON DELETE CASCADE des Assets).';

-- Korrektur-Notiz für nachtraegliche Deklarations-Korrekturen
ALTER TABLE media_asset_rights_declarations
    ADD COLUMN IF NOT EXISTS correction_note TEXT;

COMMENT ON COLUMN media_asset_rights_declarations.correction_note IS
    'Optionale Begruendung fuer action_type=correction: Warum wurde die Erklaerung korrigiert?';

-- ''correction'' action_type hinzufuegen (bestehende CHECK-Constraint ersetzen)
ALTER TABLE media_asset_rights_declarations
    DROP CONSTRAINT IF EXISTS media_asset_rights_declarations_action_type_check;

ALTER TABLE media_asset_rights_declarations
    ADD CONSTRAINT media_asset_rights_declarations_action_type_check
        CHECK (action_type IN (
            'upload',
            'promote_club',
            'promote_official',
            're_declaration',
            'legacy_re_declaration',
            'correction'
        ));
