-- Migration 017: Add capability-based task routing.
-- Workers can declare capabilities and tags, and tasks can require specific
-- capabilities/tags for routing to appropriate workers.

-- Add tags column to workers table for arbitrary metadata/labels.
-- Tags are key-value pairs that can be used for worker selection.
-- Example: {"gpu": "true", "region": "us-west"}
ALTER TABLE workers ADD COLUMN IF NOT EXISTS tags JSONB DEFAULT '{}';

COMMENT ON COLUMN workers.tags IS 'Key-value tags for worker selection (e.g., {"gpu": "true"})';

-- Add required_capabilities to work_queue for capability-based routing.
-- Tasks can require specific capabilities (from workers.capabilities array).
-- Example: ["gpu", "high-memory"]
ALTER TABLE work_queue ADD COLUMN IF NOT EXISTS required_capabilities TEXT[] DEFAULT '{}';

COMMENT ON COLUMN work_queue.required_capabilities IS 'Array of required worker capabilities for task routing';

-- Add required_tags to work_queue for tag-based routing.
-- Tasks can require workers to have specific tags.
-- Example: {"region": "us-west"}
ALTER TABLE work_queue ADD COLUMN IF NOT EXISTS required_tags JSONB DEFAULT '{}';

COMMENT ON COLUMN work_queue.required_tags IS 'Required worker tags for task routing (JSON key-value pairs)';

-- Create GIN index for capability-based routing queries.
-- Enables efficient queries like: WHERE required_capabilities <@ worker_capabilities
CREATE INDEX IF NOT EXISTS idx_work_queue_capabilities
    ON work_queue USING GIN(required_capabilities)
    WHERE required_capabilities != '{}';

-- Create GIN index for tag-based routing queries.
-- Enables efficient queries like: WHERE required_tags <@ worker_tags
CREATE INDEX IF NOT EXISTS idx_work_queue_tags
    ON work_queue USING GIN(required_tags)
    WHERE required_tags != '{}';
