-- Migration 014: Session Context for Auto-linking
-- Tracks current working task per session for automatic task relationship creation

CREATE TABLE IF NOT EXISTS session_context (
    session_id TEXT PRIMARY KEY,
    current_task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_session_context_task ON session_context(current_task_id);

-- Auto-update timestamp on changes
CREATE OR REPLACE FUNCTION update_session_context_timestamp()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER session_context_updated
    BEFORE UPDATE ON session_context
    FOR EACH ROW
    EXECUTE FUNCTION update_session_context_timestamp();

-- Record migration
INSERT INTO schema_migrations (version) VALUES ('014_session_context')
ON CONFLICT (version) DO NOTHING;
