CREATE TABLE IF NOT EXISTS public.leaudit_page_quality_runs (
    id BIGSERIAL PRIMARY KEY,
    document_id BIGINT NOT NULL,
    document_file_id BIGINT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'queued',
    summary_status VARCHAR(32) NULL,
    total_pages INTEGER NOT NULL DEFAULT 0,
    review_page_count INTEGER NOT NULL DEFAULT 0,
    reject_page_count INTEGER NOT NULL DEFAULT 0,
    skip_reason VARCHAR(64) NULL,
    task_id VARCHAR(128) NULL,
    error_message TEXT NULL,
    started_at TIMESTAMP NULL,
    finished_at TIMESTAMP NULL,
    created_by BIGINT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP NULL
);

CREATE TABLE IF NOT EXISTS public.leaudit_page_quality_results (
    id BIGSERIAL PRIMARY KEY,
    run_id BIGINT NOT NULL,
    document_id BIGINT NOT NULL,
    page_num INTEGER NOT NULL,
    quality_status VARCHAR(32) NOT NULL,
    quality_score NUMERIC(10, 4) NULL,
    reason_text TEXT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_leaudit_page_quality_runs_document_id
ON public.leaudit_page_quality_runs(document_id)
WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_leaudit_page_quality_results_run_id
ON public.leaudit_page_quality_results(run_id);
