-- Enhance task-team integration for WHOOSH Phase 2
-- Add missing columns and relationships for team composition workflow

-- Add repository_id column to tasks table if not exists 
-- (some tasks might not have this from the original migration)
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS repository_id UUID REFERENCES repositories(id) ON DELETE SET NULL;

-- Create index for repository_id if not exists
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_tasks_repository_id') THEN
        CREATE INDEX idx_tasks_repository_id ON tasks(repository_id);
    END IF;
END$$;

-- Update teams table to have better task linkage
-- Add task_id reference for current active task
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'teams' AND column_name = 'task_id') THEN
        ALTER TABLE teams ADD COLUMN task_id UUID REFERENCES tasks(id) ON DELETE SET NULL;
        CREATE INDEX idx_teams_task_id ON teams(task_id);
    END IF;
END$$;

-- Add team status tracking for better workflow management
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'teams' AND column_name = 'composition_data') THEN
        ALTER TABLE teams ADD COLUMN composition_data JSONB DEFAULT '{}';
    END IF;
END$$;

-- Add performance metrics to agents table for better team matching
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'agents' AND column_name = 'workload_capacity') THEN
        ALTER TABLE agents ADD COLUMN workload_capacity INTEGER DEFAULT 1;
        ALTER TABLE agents ADD COLUMN current_tasks INTEGER DEFAULT 0;
        ALTER TABLE agents ADD COLUMN success_rate FLOAT DEFAULT 0.0;
        
        CREATE INDEX idx_agents_workload ON agents(workload_capacity, current_tasks);
        CREATE INDEX idx_agents_performance ON agents(success_rate);
    END IF;
END$$;

-- Create task execution tracking for better monitoring
CREATE TABLE IF NOT EXISTS task_executions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    task_id UUID NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    team_id UUID NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
    agent_id UUID REFERENCES agents(id) ON DELETE SET NULL,
    
    -- Execution details
    stage VARCHAR(50) NOT NULL DEFAULT 'analysis', -- analysis, planning, execution, review, complete
    status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, in_progress, completed, failed
    
    -- Output and results
    output_data JSONB DEFAULT '{}',
    error_message TEXT,
    
    -- Timing
    started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    completed_at TIMESTAMP WITH TIME ZONE,
    duration_seconds INTEGER,
    
    -- Metadata
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for task executions
CREATE INDEX IF NOT EXISTS idx_task_executions_task_id ON task_executions(task_id);
CREATE INDEX IF NOT EXISTS idx_task_executions_team_id ON task_executions(team_id);
CREATE INDEX IF NOT EXISTS idx_task_executions_agent_id ON task_executions(agent_id);
CREATE INDEX IF NOT EXISTS idx_task_executions_status ON task_executions(status);
CREATE INDEX IF NOT EXISTS idx_task_executions_stage ON task_executions(stage);

-- Add updated_at trigger for task_executions
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'update_task_executions_updated_at') THEN
        CREATE TRIGGER update_task_executions_updated_at
            BEFORE UPDATE ON task_executions
            FOR EACH ROW
            EXECUTE FUNCTION update_updated_at_column();
    END IF;
END$$;