-- Phase 3: Orchestration — claim TTL, retry, dead letter, workflows

-- Claim TTL: track when claims expire
ALTER TABLE tasks ADD COLUMN claim_expires_at TIMESTAMPTZ;

-- Retry tracking
ALTER TABLE tasks ADD COLUMN retry_count INT NOT NULL DEFAULT 0;
ALTER TABLE tasks ADD COLUMN max_retries INT NOT NULL DEFAULT 3;
ALTER TABLE tasks ADD COLUMN last_failed_at TIMESTAMPTZ;
ALTER TABLE tasks ADD COLUMN retry_after TIMESTAMPTZ;

-- Dead letter: permanently failed tasks
ALTER TABLE tasks ADD COLUMN dead_letter BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE tasks ADD COLUMN dead_letter_reason TEXT;

-- Index for claim expiry sweeps
CREATE INDEX idx_tasks_claim_expires ON tasks(claim_expires_at)
    WHERE status = 'claimed' AND claim_expires_at IS NOT NULL;

-- Index for retry sweeps
CREATE INDEX idx_tasks_retry_after ON tasks(retry_after)
    WHERE status = 'failed' AND retry_after IS NOT NULL AND dead_letter = FALSE;

-- Workflow state table
CREATE TABLE workflow_runs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id UUID NOT NULL REFERENCES projects(id),
    workflow_name TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'running',
    current_step TEXT NOT NULL DEFAULT '',
    inputs JSONB DEFAULT '{}',
    state JSONB DEFAULT '{}',
    outputs JSONB DEFAULT '{}',
    error TEXT,
    started_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ,
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_workflow_runs_project ON workflow_runs(project_id, status);

-- Workflow step log (audit trail)
CREATE TABLE workflow_steps (
    id BIGSERIAL PRIMARY KEY,
    run_id UUID NOT NULL REFERENCES workflow_runs(id) ON DELETE CASCADE,
    step_name TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'running',
    inputs JSONB DEFAULT '{}',
    outputs JSONB DEFAULT '{}',
    error TEXT,
    started_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ
);

CREATE INDEX idx_workflow_steps_run ON workflow_steps(run_id);
