-- Migration 004: UCCA Escalation Workflow
-- Implements E0-E3 escalation levels with DSB routing

-- ============================================================================
-- Escalation Levels (Reference)
-- ============================================================================
-- E0: Auto-Approve     - Only INFO rules triggered, Risk < 20
-- E1: Team-Lead Review - WARN rules OR Risk 20-40
-- E2: DSB Consultation - Art. 9 data OR Risk 40-60 OR DSFA recommended
-- E3: DSB + Legal      - BLOCK rules OR Risk > 60 OR Art. 22 risk

-- ============================================================================
-- Escalation Queue Table
-- ============================================================================

CREATE TABLE IF NOT EXISTS ucca_escalations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES compliance_tenants(id) ON DELETE CASCADE,
    assessment_id UUID NOT NULL REFERENCES ucca_assessments(id) ON DELETE CASCADE,

    -- Escalation Level
    escalation_level VARCHAR(10) NOT NULL CHECK (escalation_level IN ('E0', 'E1', 'E2', 'E3')),
    escalation_reason TEXT NOT NULL,

    -- Routing
    assigned_to UUID,                          -- User ID of assignee (DSB, Team Lead, etc.)
    assigned_role VARCHAR(50),                 -- Role for assignment (dsb, team_lead, legal)
    assigned_at TIMESTAMPTZ,

    -- Status
    status VARCHAR(30) NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'assigned', 'in_review', 'approved', 'rejected', 'returned')),

    -- Review
    reviewer_id UUID,
    reviewer_notes TEXT,
    reviewed_at TIMESTAMPTZ,

    -- Decision
    decision VARCHAR(20) CHECK (decision IN ('approve', 'reject', 'modify', 'escalate')),
    decision_notes TEXT,
    decision_at TIMESTAMPTZ,

    -- Conditions for approval
    conditions JSONB DEFAULT '[]',             -- Array of conditions that must be met

    -- Timestamps
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    due_date TIMESTAMPTZ,                      -- SLA deadline

    -- Notifications sent
    notification_sent BOOLEAN DEFAULT FALSE,
    notification_sent_at TIMESTAMPTZ
);

-- ============================================================================
-- Escalation History (Audit Trail)
-- ============================================================================

CREATE TABLE IF NOT EXISTS ucca_escalation_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    escalation_id UUID NOT NULL REFERENCES ucca_escalations(id) ON DELETE CASCADE,

    -- What changed
    action VARCHAR(50) NOT NULL,               -- created, assigned, reviewed, decided, escalated, etc.
    old_status VARCHAR(30),
    new_status VARCHAR(30),
    old_level VARCHAR(10),
    new_level VARCHAR(10),

    -- Who and when
    actor_id UUID NOT NULL,
    actor_role VARCHAR(50),
    notes TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- ============================================================================
-- DSB Assignment Pool
-- ============================================================================

CREATE TABLE IF NOT EXISTS ucca_dsb_pool (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES compliance_tenants(id) ON DELETE CASCADE,
    user_id UUID NOT NULL,
    user_name VARCHAR(255) NOT NULL,
    user_email VARCHAR(255) NOT NULL,
    role VARCHAR(50) NOT NULL DEFAULT 'dsb',   -- dsb, deputy_dsb, legal
    is_active BOOLEAN DEFAULT TRUE,
    max_concurrent_reviews INT DEFAULT 10,
    current_reviews INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(tenant_id, user_id)
);

-- ============================================================================
-- SLA Configuration per Escalation Level
-- ============================================================================

CREATE TABLE IF NOT EXISTS ucca_escalation_sla (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES compliance_tenants(id) ON DELETE CASCADE,
    escalation_level VARCHAR(10) NOT NULL CHECK (escalation_level IN ('E0', 'E1', 'E2', 'E3')),

    -- SLA settings
    response_hours INT NOT NULL DEFAULT 24,    -- Hours to first response
    resolution_hours INT NOT NULL DEFAULT 72,  -- Hours to resolution

    -- Notification settings
    notify_on_creation BOOLEAN DEFAULT TRUE,
    notify_on_approaching_sla BOOLEAN DEFAULT TRUE,
    notify_on_sla_breach BOOLEAN DEFAULT TRUE,
    approaching_sla_hours INT DEFAULT 8,       -- Notify X hours before SLA breach

    -- Auto-escalation
    auto_escalate_on_breach BOOLEAN DEFAULT FALSE,

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(tenant_id, escalation_level)
);

-- ============================================================================
-- Indexes
-- ============================================================================

-- Fast lookup by tenant and status
CREATE INDEX idx_ucca_escalations_tenant_status ON ucca_escalations(tenant_id, status);

-- Fast lookup by assignee
CREATE INDEX idx_ucca_escalations_assigned ON ucca_escalations(assigned_to, status);

-- Fast lookup by assessment
CREATE INDEX idx_ucca_escalations_assessment ON ucca_escalations(assessment_id);

-- SLA monitoring (find escalations approaching or past due date)
CREATE INDEX idx_ucca_escalations_due ON ucca_escalations(due_date) WHERE status NOT IN ('approved', 'rejected');

-- History lookup
CREATE INDEX idx_ucca_escalation_history_escalation ON ucca_escalation_history(escalation_id);

-- DSB pool lookup
CREATE INDEX idx_ucca_dsb_pool_tenant ON ucca_dsb_pool(tenant_id, is_active);

-- ============================================================================
-- Default SLA Values (inserted on first use)
-- ============================================================================

-- Note: These will be inserted per-tenant when needed via application logic
-- E0: Auto-approve, no SLA
-- E1: 24h response, 72h resolution
-- E2: 8h response, 48h resolution
-- E3: 4h response, 24h resolution (urgent)

-- ============================================================================
-- Comments
-- ============================================================================

COMMENT ON TABLE ucca_escalations IS 'UCCA escalation queue for assessments requiring review';
COMMENT ON COLUMN ucca_escalations.escalation_level IS 'E0=Auto, E1=Team, E2=DSB, E3=DSB+Legal';
COMMENT ON COLUMN ucca_escalations.conditions IS 'JSON array of conditions required for approval';
COMMENT ON TABLE ucca_escalation_history IS 'Audit trail of all escalation state changes';
COMMENT ON TABLE ucca_dsb_pool IS 'Pool of DSB/Legal reviewers for assignment';
COMMENT ON TABLE ucca_escalation_sla IS 'SLA configuration per escalation level per tenant';
