"""add durable periodic report job fields

Revision ID: 0021_periodic_report_async_jobs
Revises: 0020_question_insight_store
Create Date: 2026-07-31 00:00:00.000000
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "0021_periodic_report_async_jobs"
down_revision = "0020_question_insight_store"
branch_labels = None
depends_on = None


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


def downgrade() -> None:
    op.execute("UPDATE sys_entitlement_plan SET status = 1 WHERE plan_type = 'teacher'")
    op.drop_index("ix_periodic_report_job_stale", table_name="sys_periodic_report")
    op.drop_index("ix_periodic_report_job_due", table_name="sys_periodic_report")
    op.drop_column("sys_periodic_report", "finished_at")
    op.drop_column("sys_periodic_report", "last_started_at")
    op.drop_column("sys_periodic_report", "locked_by")
    op.drop_column("sys_periodic_report", "locked_at")
    op.drop_column("sys_periodic_report", "next_run_at")
    op.drop_column("sys_periodic_report", "max_attempts")
    op.drop_column("sys_periodic_report", "attempt_count")
