-- NV2: Parallel embedding subsystem job table
-- Additive and independent from the legacy/transitional vectorization flow.

CREATE TABLE IF NOT EXISTS DOC.doc_embedding_job (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    document_id UUID NOT NULL REFERENCES DOC.doc_document(id) ON DELETE CASCADE,
    representation_id UUID NOT NULL REFERENCES DOC.doc_text_representation(id) ON DELETE CASCADE,
    model_key VARCHAR(255) NOT NULL,
    job_type VARCHAR(32) NOT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
    attempt_count INTEGER NOT NULL DEFAULT 0,
    next_retry_at TIMESTAMP WITH TIME ZONE,
    priority INTEGER NOT NULL DEFAULT 0,
    provider_request_id VARCHAR(255),
    last_error TEXT,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_doc_embedding_job_status_next_retry
    ON DOC.doc_embedding_job(status, next_retry_at);

CREATE INDEX IF NOT EXISTS idx_doc_embedding_job_representation
    ON DOC.doc_embedding_job(representation_id);

CREATE INDEX IF NOT EXISTS idx_doc_embedding_job_document
    ON DOC.doc_embedding_job(document_id);

CREATE INDEX IF NOT EXISTS idx_doc_embedding_job_model_key
    ON DOC.doc_embedding_job(model_key);
