"""add durable topic settlement job fields

Revision ID: 0024_topic_settlement_jobs
Revises: 0023_simple_knowledge_route
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "0024_topic_settlement_jobs"
down_revision = "0023_simple_knowledge_route"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column(
        "sys_topic_summary",
        sa.Column("attempt_count", sa.Integer(), nullable=False, server_default="0"),
    )
    op.add_column(
        "sys_topic_summary",
        sa.Column("max_attempts", sa.Integer(), nullable=False, server_default="3"),
    )
    op.add_column("sys_topic_summary", sa.Column("next_run_at", sa.DateTime(), nullable=True))
    op.add_column("sys_topic_summary", sa.Column("locked_at", sa.DateTime(), nullable=True))
    op.add_column("sys_topic_summary", sa.Column("locked_by", sa.String(length=120), nullable=True))
    op.add_column("sys_topic_summary", sa.Column("last_started_at", sa.DateTime(), nullable=True))
    op.add_column("sys_topic_summary", sa.Column("finished_at", sa.DateTime(), nullable=True))
    op.execute(
        "UPDATE sys_topic_summary "
        "SET finished_at = generated_at "
        "WHERE status IN ('success', 'fallback', 'failed')"
    )
    op.create_index(
        "ix_topic_summary_job_due",
        "sys_topic_summary",
        ["status", "next_run_at", "id"],
    )
    op.create_index(
        "ix_topic_summary_job_stale",
        "sys_topic_summary",
        ["status", "locked_at"],
    )


def downgrade() -> None:
    op.drop_index("ix_topic_summary_job_stale", table_name="sys_topic_summary")
    op.drop_index("ix_topic_summary_job_due", table_name="sys_topic_summary")
    op.drop_column("sys_topic_summary", "finished_at")
    op.drop_column("sys_topic_summary", "last_started_at")
    op.drop_column("sys_topic_summary", "locked_by")
    op.drop_column("sys_topic_summary", "locked_at")
    op.drop_column("sys_topic_summary", "next_run_at")
    op.drop_column("sys_topic_summary", "max_attempts")
    op.drop_column("sys_topic_summary", "attempt_count")
