-- Workflow Relations Schema
-- Stores semantic relations between workflow canvas nodes with versioning support

-- Table for storing workflow relations with relation wording
CREATE TABLE IF NOT EXISTS workflow_relations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    workflow_id VARCHAR(255) NOT NULL,
    version INTEGER NOT NULL,
    source_node_id VARCHAR(255) NOT NULL,
    target_node_id VARCHAR(255) NOT NULL,
    relation_type VARCHAR(50) NOT NULL, -- data-flow, dependency, conditional, parallel
    label TEXT NOT NULL,
    relation_wording JSONB NOT NULL, -- {verb, source_output, target_input, connection_type, confidence, semantic_match}
    metadata JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE,
    UNIQUE(workflow_id, source_node_id, target_node_id, version)
);

-- Table for versioned history of relation changes
CREATE TABLE IF NOT EXISTS workflow_relation_versions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    workflow_id VARCHAR(255) NOT NULL,
    edge_id VARCHAR(255) NOT NULL,
    version_num INTEGER NOT NULL,
    operation VARCHAR(10) NOT NULL, -- CREATE, UPDATE, DELETE
    snapshot JSONB NOT NULL,
    changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    changed_by VARCHAR(255),
    fields_changed JSONB, -- ["field1", "field2"]
    FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE,
    UNIQUE(workflow_id, edge_id, version_num)
);

-- Table for GraphRAG indexing metadata
CREATE TABLE IF NOT EXISTS workflow_rag_index (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    workflow_id VARCHAR(255) NOT NULL UNIQUE,
    version INTEGER NOT NULL,
    indexed_status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, indexed, partial, failed
    embedding_model VARCHAR(100),
    last_indexed_at TIMESTAMP,
    index_metadata JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE
);

-- Indexes for performance
CREATE INDEX idx_workflow_relations_workflow_version ON workflow_relations(workflow_id, version);
CREATE INDEX idx_workflow_relations_type ON workflow_relations(relation_type);
CREATE INDEX idx_workflow_relations_nodes ON workflow_relations(source_node_id, target_node_id);
CREATE INDEX idx_workflow_relation_versions_workflow_edge ON workflow_relation_versions(workflow_id, edge_id);
CREATE INDEX idx_workflow_relation_versions_operation ON workflow_relation_versions(operation);
CREATE INDEX idx_workflow_rag_index_status ON workflow_rag_index(indexed_status);
