-- Tasks table for generic task management
-- Supports GITEA, GitHub, Jira, and other task sources
CREATE TABLE tasks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    external_id VARCHAR(255) NOT NULL, -- GITEA issue ID, GitHub issue ID, etc.
    external_url TEXT NOT NULL, -- Full URL to external task
    source_type VARCHAR(50) NOT NULL DEFAULT 'gitea', -- 'gitea', 'github', 'jira', 'manual'
    source_config JSONB DEFAULT '{}', -- Source-specific configuration
    
    -- Core task data
    title VARCHAR(500) NOT NULL,
    description TEXT,
    status VARCHAR(50) NOT NULL DEFAULT 'open',
    priority VARCHAR(20) NOT NULL DEFAULT 'medium',
    
    -- Assignment and team data
    assigned_team_id UUID REFERENCES teams(id) ON DELETE SET NULL,
    assigned_agent_id UUID REFERENCES agents(id) ON DELETE SET NULL,
    
    -- Repository and project context
    repository VARCHAR(255), -- e.g., "owner/repo" 
    project_id VARCHAR(255),
    
    -- Task metadata
    labels JSONB DEFAULT '[]',
    tech_stack JSONB DEFAULT '[]',
    requirements JSONB DEFAULT '[]',
    estimated_hours INTEGER,
    complexity_score FLOAT,
    
    -- Workflow tracking
    claimed_at TIMESTAMP WITH TIME ZONE,
    started_at TIMESTAMP WITH TIME ZONE,
    completed_at TIMESTAMP WITH TIME ZONE,
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    external_created_at TIMESTAMP WITH TIME ZONE,
    external_updated_at TIMESTAMP WITH TIME ZONE,
    
    -- Constraints
    UNIQUE(external_id, source_type) -- Prevent duplicate external tasks
);

-- Indexes for performance
CREATE INDEX idx_tasks_status ON tasks(status);
CREATE INDEX idx_tasks_source_type ON tasks(source_type);
CREATE INDEX idx_tasks_assigned_team ON tasks(assigned_team_id);
CREATE INDEX idx_tasks_assigned_agent ON tasks(assigned_agent_id);
CREATE INDEX idx_tasks_repository ON tasks(repository);
CREATE INDEX idx_tasks_priority ON tasks(priority);
CREATE INDEX idx_tasks_created_at ON tasks(created_at);
CREATE INDEX idx_tasks_external_id_source ON tasks(external_id, source_type);

-- Update teams table to link back to tasks
ALTER TABLE teams ADD COLUMN IF NOT EXISTS current_task_id UUID REFERENCES tasks(id) ON DELETE SET NULL;