CREATE TABLE IF NOT EXISTS _runat_jobs (
    id UUID PRIMARY KEY,
    job_type VARCHAR(255) NOT NULL,
    payload JSONB NOT NULL,
    job_schedule JSONB NOT NULL,
    retry JSONB NOT NULL,
    status INTEGER NOT NULL DEFAULT 0,
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 3,
    scheduled_at TIMESTAMPTZ NOT NULL,
    locked_until TIMESTAMPTZ,
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Primary index for claim_next_job query - covers status, scheduled_at, and locked_until filtering
CREATE INDEX IF NOT EXISTS idx__runat_jobs_claim ON _runat_jobs(scheduled_at, locked_until) WHERE status = 0;
