"""add_version_to_meetings

Revision ID: m7n8o9p0q1r2
Revises: k5f6g7h8i9j0
Create Date: 2025-12-29 14:00:00.000000

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    """Add version column to meetings table for optimistic locking.

    This column tracks entity version for optimistic concurrency control.
    Default value is 1 for all existing and new meetings.
    """
    # Check if column already exists (idempotency)
    conn = op.get_bind()
    result = conn.execute(
        sa.text(
            "SELECT EXISTS ("
            "SELECT 1 FROM information_schema.columns "
            "WHERE table_schema = 'noteflow' "
            "AND table_name = 'meetings' "
            "AND column_name = 'version'"
            ")"
        )
    )
    if not result.scalar():
        op.add_column(
            "meetings",
            sa.Column("version", sa.Integer(), nullable=False, server_default="1"),
            schema="noteflow",
        )


def downgrade() -> None:
    """Remove version column from meetings table."""
    op.drop_column("meetings", "version", schema="noteflow")
