-- Migration 038: Change-Request System
-- Central inbox for compliance changes triggered by events or manual creation

BEGIN;

-- ============================================================================
-- 1. Change Requests Table
-- ============================================================================

CREATE TABLE IF NOT EXISTS compliance_change_requests (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    -- Trigger source
    trigger_type VARCHAR(50) NOT NULL DEFAULT 'manual',
    trigger_source_id UUID,
    -- Target document
    target_document_type VARCHAR(50) NOT NULL,
    target_document_id UUID,
    target_section VARCHAR(100),
    -- Proposal
    proposal_title VARCHAR(500) NOT NULL,
    proposal_body TEXT,
    proposed_changes JSONB DEFAULT '{}'::jsonb,
    -- Workflow
    status VARCHAR(30) NOT NULL DEFAULT 'pending',
    priority VARCHAR(20) DEFAULT 'normal',
    decided_by VARCHAR(200),
    decided_at TIMESTAMPTZ,
    rejection_reason TEXT,
    resulting_version_id UUID,
    -- Soft delete
    is_deleted BOOLEAN DEFAULT FALSE,
    -- Metadata
    created_by VARCHAR(200) DEFAULT 'system',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    CONSTRAINT chk_cr_status CHECK (status IN ('pending', 'accepted', 'rejected', 'edited_and_accepted')),
    CONSTRAINT chk_cr_priority CHECK (priority IN ('low', 'normal', 'high', 'critical')),
    CONSTRAINT chk_cr_doc_type CHECK (target_document_type IN ('dsfa', 'vvt', 'tom', 'loeschfristen', 'obligation'))
);

CREATE INDEX IF NOT EXISTS idx_cr_tenant ON compliance_change_requests(tenant_id);
CREATE INDEX IF NOT EXISTS idx_cr_status ON compliance_change_requests(tenant_id, status) WHERE NOT is_deleted;
CREATE INDEX IF NOT EXISTS idx_cr_doc_type ON compliance_change_requests(tenant_id, target_document_type) WHERE NOT is_deleted;
CREATE INDEX IF NOT EXISTS idx_cr_priority ON compliance_change_requests(tenant_id, priority) WHERE status = 'pending' AND NOT is_deleted;

-- ============================================================================
-- 2. Audit Log for Change Requests
-- ============================================================================

CREATE TABLE IF NOT EXISTS compliance_change_request_audit (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    change_request_id UUID NOT NULL REFERENCES compliance_change_requests(id) ON DELETE CASCADE,
    tenant_id VARCHAR(255) NOT NULL,
    action VARCHAR(50) NOT NULL,
    performed_by VARCHAR(200) DEFAULT 'system',
    before_state JSONB,
    after_state JSONB,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_cra_cr ON compliance_change_request_audit(change_request_id);

COMMIT;
