"""Add async_jobs table for background job execution.

Revision ID: m6_003_async_jobs_table
Revises: m6_002_merge_safety_and_checkpoint
Create Date: 2026-03-03 00:00:00

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "m6_003_async_jobs_table"
down_revision: str | Sequence[str] | None = "m6_002_merge_safety_and_checkpoint"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create the async_jobs table."""
    op.create_table(
        "async_jobs",
        sa.Column("job_id", sa.String(26), primary_key=True),
        sa.Column("plan_id", sa.String(26), nullable=False),
        sa.Column("phase", sa.String(20), nullable=False),
        sa.Column("status", sa.String(20), nullable=False, server_default="queued"),
        sa.Column("payload_json", sa.Text(), nullable=False, server_default="{}"),
        sa.Column("created_at", sa.String(30), nullable=False),
        sa.Column("started_at", sa.String(30), nullable=True),
        sa.Column("finished_at", sa.String(30), nullable=True),
        sa.Column("worker_id", sa.String(255), nullable=True),
        sa.Column("last_heartbeat", sa.String(30), nullable=True),
        sa.Column("schema_version", sa.Integer(), nullable=False, server_default="1"),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.CheckConstraint(
            "status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled')",
            name="ck_async_jobs_status",
        ),
        sa.CheckConstraint(
            "phase IN ('execute', 'apply')",
            name="ck_async_jobs_phase",
        ),
    )
    op.create_index("ix_async_jobs_plan_id", "async_jobs", ["plan_id"])
    op.create_index("ix_async_jobs_status", "async_jobs", ["status"])
    op.create_index("ix_async_jobs_worker_id", "async_jobs", ["worker_id"])
    op.create_index("ix_async_jobs_created_at", "async_jobs", ["created_at"])


def downgrade() -> None:
    """Drop the async_jobs table."""
    op.drop_index("ix_async_jobs_created_at", table_name="async_jobs")
    op.drop_index("ix_async_jobs_worker_id", table_name="async_jobs")
    op.drop_index("ix_async_jobs_status", table_name="async_jobs")
    op.drop_index("ix_async_jobs_plan_id", table_name="async_jobs")
    op.drop_table("async_jobs")
