-- Phase 6: Temporal Workflow Service Integration
--
-- Adds reference/linking table for external Temporal.io workflows.
-- Temporal Service owns execution state; Memory DB owns reasoning traces.
--
-- This is a minimal linking schema - no duplication of workflow logic.

-- ─────────────────────────────────────────────────────────────────────────────
-- Temporal Workflow Links (External Service Reference)
-- ─────────────────────────────────────────────────────────────────────────────

CREATE TABLE IF NOT EXISTS temporal_workflow_links (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    
    -- Temporal Service Reference (Required)
    workflow_id VARCHAR(255) NOT NULL,      -- Temporal workflow ID
    workflow_type VARCHAR(255),             -- e.g., "entity_extraction", "synthesis"
    run_id VARCHAR(255),                    -- Temporal run ID
    
    -- Memory Entity References (Optional - NULL until linked)
    entity_id UUID REFERENCES memory_entity(id) ON DELETE SET NULL,
    edge_id UUID REFERENCES memory_edge(id) ON DELETE SET NULL,
    node_id BIGINT REFERENCES memory_node(id) ON DELETE SET NULL,
    
    -- Sync Status
    status VARCHAR(50) NOT NULL DEFAULT 'active' 
        CHECK (status IN ('active', 'completed', 'failed', 'archived')),
    
    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_synced_at TIMESTAMPTZ,
    
    -- Metadata (Extra context, error details, etc.)
    metadata JSONB
);

-- Indexes for common queries
CREATE INDEX IF NOT EXISTS idx_temporal_workflow_id 
    ON temporal_workflow_links(workflow_id);

CREATE INDEX IF NOT EXISTS idx_temporal_entity_id 
    ON temporal_workflow_links(entity_id) 
    WHERE entity_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_temporal_edge_id 
    ON temporal_workflow_links(edge_id) 
    WHERE edge_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_temporal_node_id 
    ON temporal_workflow_links(node_id) 
    WHERE node_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_temporal_status 
    ON temporal_workflow_links(status, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_temporal_workflow_type 
    ON temporal_workflow_links(workflow_type) 
    WHERE status = 'active';

-- ─────────────────────────────────────────────────────────────────────────────
-- Rollback Instructions
-- ─────────────────────────────────────────────────────────────────────────────

-- To rollback this migration:
--
-- DROP INDEX IF EXISTS idx_temporal_workflow_type;
-- DROP INDEX IF EXISTS idx_temporal_status;
-- DROP INDEX IF EXISTS idx_temporal_node_id;
-- DROP INDEX IF EXISTS idx_temporal_edge_id;
-- DROP INDEX IF EXISTS idx_temporal_entity_id;
-- DROP INDEX IF EXISTS idx_temporal_workflow_id;
-- DROP TABLE IF EXISTS temporal_workflow_links;
