CREATE TABLE feedback_summary_runs (
    id UUID PRIMARY KEY,
    feedback_session_id UUID NOT NULL REFERENCES feedback_sessions(id) ON DELETE CASCADE,
    idempotency_key VARCHAR(100) NOT NULL UNIQUE,
    status VARCHAR(16) NOT NULL DEFAULT 'queued',
    existing_content TEXT NOT NULL DEFAULT '',
    source_hash VARCHAR(64),
    content TEXT,
    method VARCHAR(24),
    model TEXT,
    prompt_version VARCHAR(32) NOT NULL DEFAULT 'summary-v1',
    character_count INTEGER,
    error_class VARCHAR(64),
    error_message TEXT,
    attempts INTEGER NOT NULL DEFAULT 0,
    processing_started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    applied_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT feedback_summary_runs_status_check
        CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'applied')),
    CONSTRAINT feedback_summary_runs_idempotency_key_check
        CHECK (char_length(idempotency_key) BETWEEN 1 AND 100),
    CONSTRAINT feedback_summary_runs_existing_content_check
        CHECK (char_length(existing_content) <= 2000),
    CONSTRAINT feedback_summary_runs_content_check
        CHECK (content IS NULL OR char_length(content) <= 2000),
    CONSTRAINT feedback_summary_runs_character_count_check
        CHECK (character_count IS NULL OR character_count BETWEEN 0 AND 2000),
    CONSTRAINT feedback_summary_runs_attempts_check
        CHECK (attempts >= 0),
    CONSTRAINT feedback_summary_runs_result_check
        CHECK (
            (status IN ('ready', 'applied') AND content IS NOT NULL AND character_count IS NOT NULL AND completed_at IS NOT NULL)
            OR
            (status NOT IN ('ready', 'applied') AND content IS NULL AND character_count IS NULL)
        )
);

CREATE TABLE feedback_summary_run_lessons (
    summary_run_id UUID NOT NULL REFERENCES feedback_summary_runs(id) ON DELETE CASCADE,
    lesson_session_id UUID NOT NULL REFERENCES lesson_sessions(id) ON DELETE CASCADE,
    PRIMARY KEY (summary_run_id, lesson_session_id)
);

CREATE INDEX idx_feedback_summary_runs_session_created
    ON feedback_summary_runs(feedback_session_id, created_at DESC);

CREATE INDEX idx_feedback_summary_runs_queue
    ON feedback_summary_runs(created_at, id)
    WHERE status IN ('queued', 'processing');

CREATE INDEX idx_feedback_summary_run_lessons_lesson
    ON feedback_summary_run_lessons(lesson_session_id);
