-- Process Manager: Recurring compliance tasks with audit trail
-- Migration 052

CREATE TABLE compliance_process_tasks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    project_id UUID,
    task_code VARCHAR(50) NOT NULL,
    title VARCHAR(500) NOT NULL,
    description TEXT,
    category VARCHAR(50) NOT NULL
        CHECK (category IN ('dsgvo','nis2','bsi','iso27001','ai_act','internal')),
    priority VARCHAR(20) NOT NULL DEFAULT 'medium'
        CHECK (priority IN ('critical','high','medium','low')),
    frequency VARCHAR(20) NOT NULL DEFAULT 'yearly'
        CHECK (frequency IN ('weekly','monthly','quarterly','semi_annual','yearly','once')),
    assigned_to VARCHAR(255),
    responsible_team VARCHAR(255),
    linked_control_ids JSONB DEFAULT '[]',
    linked_module VARCHAR(100),
    last_completed_at TIMESTAMPTZ,
    next_due_date DATE,
    due_reminder_days INTEGER DEFAULT 14,
    status VARCHAR(20) NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending','in_progress','completed','overdue','skipped')),
    completion_date TIMESTAMPTZ,
    completion_result TEXT,
    completion_evidence_id UUID,
    follow_up_actions JSONB DEFAULT '[]',
    is_seed BOOLEAN DEFAULT FALSE,
    notes TEXT,
    tags JSONB DEFAULT '[]',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_id, project_id, task_code)
);

CREATE TABLE compliance_process_task_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    task_id UUID NOT NULL REFERENCES compliance_process_tasks(id) ON DELETE CASCADE,
    completed_by VARCHAR(255),
    completed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    result TEXT,
    evidence_id UUID,
    notes TEXT,
    status VARCHAR(20) NOT NULL
);

CREATE INDEX idx_process_tasks_tenant ON compliance_process_tasks(tenant_id);
CREATE INDEX idx_process_tasks_status ON compliance_process_tasks(status);
CREATE INDEX idx_process_tasks_due ON compliance_process_tasks(next_due_date);
CREATE INDEX idx_process_tasks_category ON compliance_process_tasks(category);
CREATE INDEX idx_task_history_task ON compliance_process_task_history(task_id);
