CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS ai_jobs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    owner_service TEXT NOT NULL,
    owner_ref TEXT NOT NULL,
    task_type TEXT NOT NULL,
    model_profile TEXT NOT NULL,
    priority INTEGER NOT NULL DEFAULT 0,
    status TEXT NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'running', 'done', 'failed', 'cancelled')),
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 3,
    input JSONB NOT NULL DEFAULT '{}'::jsonb,
    result JSONB,
    error_code TEXT,
    error_message TEXT,
    scheduled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    worker_id TEXT,
    heartbeat_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    idempotency_key TEXT
);

CREATE UNIQUE INDEX IF NOT EXISTS ai_jobs_idempotency_key_idx
    ON ai_jobs (idempotency_key)
    WHERE idempotency_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS ai_jobs_queue_idx
    ON ai_jobs (status, priority DESC, scheduled_at ASC, created_at ASC)
    WHERE status IN ('pending', 'running');

CREATE INDEX IF NOT EXISTS ai_jobs_owner_idx
    ON ai_jobs (owner_service, owner_ref);

CREATE INDEX IF NOT EXISTS ai_jobs_error_idx
    ON ai_jobs (task_type, model_profile, error_code, updated_at DESC)
    WHERE status = 'failed';
