-- Vollständiges Basisschema: Dokument-Stammsatz und Versuchshistorie.
-- Dieses Skript wird für neue Datenbanken ausgeführt (Fall 1).
-- Für bestehende Datenbanken mit konformem Schema wird nur eine Flyway-Baseline
-- eingetragen; das Skript wird in diesem Fall NICHT ausgeführt (Fall 2).

CREATE TABLE document_record (
    id                          INTEGER PRIMARY KEY AUTOINCREMENT,
    fingerprint                 TEXT    NOT NULL,
    last_known_source_locator   TEXT    NOT NULL,
    last_known_source_file_name TEXT    NOT NULL,
    overall_status              TEXT    NOT NULL,
    content_error_count         INTEGER NOT NULL DEFAULT 0,
    transient_error_count       INTEGER NOT NULL DEFAULT 0,
    last_failure_instant        TEXT,
    last_success_instant        TEXT,
    created_at                  TEXT    NOT NULL,
    updated_at                  TEXT    NOT NULL,
    last_target_path            TEXT,
    last_target_file_name       TEXT,
    CONSTRAINT uq_document_record_fingerprint UNIQUE (fingerprint)
);

CREATE TABLE processing_attempt (
    id                     INTEGER PRIMARY KEY AUTOINCREMENT,
    fingerprint            TEXT    NOT NULL,
    run_id                 TEXT    NOT NULL,
    attempt_number         INTEGER NOT NULL,
    started_at             TEXT    NOT NULL,
    ended_at               TEXT    NOT NULL,
    status                 TEXT    NOT NULL,
    failure_class          TEXT,
    failure_message        TEXT,
    retryable              INTEGER NOT NULL DEFAULT 0,
    model_name             TEXT,
    prompt_identifier      TEXT,
    processed_page_count   INTEGER,
    sent_character_count   INTEGER,
    ai_raw_response        TEXT,
    ai_reasoning           TEXT,
    resolved_date          TEXT,
    date_source            TEXT,
    validated_title        TEXT,
    final_target_file_name TEXT,
    ai_provider            TEXT,
    CONSTRAINT fk_processing_attempt_fingerprint
        FOREIGN KEY (fingerprint) REFERENCES document_record (fingerprint),
    CONSTRAINT uq_processing_attempt_fingerprint_number
        UNIQUE (fingerprint, attempt_number)
);

CREATE INDEX idx_processing_attempt_fingerprint
    ON processing_attempt (fingerprint);

CREATE INDEX idx_processing_attempt_run_id
    ON processing_attempt (run_id);

CREATE INDEX idx_document_record_overall_status
    ON document_record (overall_status);
