-- Create command_queue table for async command execution
CREATE TABLE IF NOT EXISTS command_queue (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id       TEXT NOT NULL,
    command          TEXT NOT NULL,
    command_type     VARCHAR(20) NOT NULL, -- 'claude', 'shell', 'git'
    working_dir      TEXT,
    status           VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, running, completed, failed, cancelled
    priority         INT NOT NULL DEFAULT 0,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    started_at       TIMESTAMPTZ,
    completed_at     TIMESTAMPTZ,
    result_exit_code INT,
    result_output    TEXT,
    result_error     TEXT,
    api_key_id       TEXT -- For audit trail, references the key that enqueued the command
);

-- Index for efficient queue queries: fetch pending commands by project ordered by priority
CREATE INDEX IF NOT EXISTS idx_command_queue_project_status
    ON command_queue(project_id, status, priority DESC, created_at ASC);

-- Index for looking up commands by status (for monitoring/admin)
CREATE INDEX IF NOT EXISTS idx_command_queue_status
    ON command_queue(status);

-- Index for cleanup of old completed commands
CREATE INDEX IF NOT EXISTS idx_command_queue_completed_at
    ON command_queue(completed_at)
    WHERE completed_at IS NOT NULL;

-- Index for audit trail by API key
CREATE INDEX IF NOT EXISTS idx_command_queue_api_key
    ON command_queue(api_key_id)
    WHERE api_key_id IS NOT NULL;

COMMENT ON TABLE command_queue IS 'Queued commands for async execution per project';
COMMENT ON COLUMN command_queue.project_id IS 'Target project ID for command execution';
COMMENT ON COLUMN command_queue.command IS 'The command to execute (prompt for claude, command for shell, JSON args for git)';
COMMENT ON COLUMN command_queue.command_type IS 'Type of command: claude, shell, or git';
COMMENT ON COLUMN command_queue.working_dir IS 'Optional working directory for command execution';
COMMENT ON COLUMN command_queue.status IS 'Command status: pending, running, completed, failed, cancelled';
COMMENT ON COLUMN command_queue.priority IS 'Priority level (higher = more urgent, 0 = default)';
COMMENT ON COLUMN command_queue.result_exit_code IS 'Exit code from command execution';
COMMENT ON COLUMN command_queue.result_output IS 'Stdout from command execution';
COMMENT ON COLUMN command_queue.result_error IS 'Stderr or error message from command execution';
COMMENT ON COLUMN command_queue.api_key_id IS 'API key ID that enqueued this command (for audit)';
