-- migrations/20250710201933_create_script_dependencies.sql

-- This table stores the dependency graph for table scripts
-- More efficient design with better indexing
CREATE TABLE script_dependencies (
    id BIGSERIAL PRIMARY KEY,
    
    -- The script that creates this dependency
    script_id BIGINT NOT NULL REFERENCES table_scripts(id) ON DELETE CASCADE,
    
    -- The table that depends on another (source of dependency)
    source_table_id BIGINT NOT NULL REFERENCES table_definitions(id) ON DELETE CASCADE,
    
    -- The table being depended upon (target of dependency)  
    target_table_id BIGINT NOT NULL REFERENCES table_definitions(id) ON DELETE CASCADE,
    
    -- What type of dependency (for better debugging)
    dependency_type TEXT NOT NULL CHECK (dependency_type IN ('column_access', 'sql_query', 'indexed_access')),
    
    -- Additional context (column name, query snippet, etc.)
    context_info JSONB,
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    
    -- Prevent duplicate dependencies for the same script
    UNIQUE (script_id, source_table_id, target_table_id, dependency_type)
);

-- Optimized indexes for fast cycle detection
CREATE INDEX idx_script_deps_source_target ON script_dependencies (source_table_id, target_table_id);
CREATE INDEX idx_script_deps_by_script ON script_dependencies (script_id);
CREATE INDEX idx_script_deps_by_target ON script_dependencies (target_table_id);

-- View for easy dependency analysis
CREATE VIEW dependency_graph AS
SELECT 
    sd.source_table_id,
    sd.target_table_id,
    st.table_name AS source_table,
    tt.table_name AS target_table,
    sd.dependency_type,
    sd.context_info,
    s.name AS schema_name
FROM script_dependencies sd
JOIN table_definitions st ON sd.source_table_id = st.id
JOIN table_definitions tt ON sd.target_table_id = tt.id  
JOIN schemas s ON st.schema_id = s.id;
