"""release_a_clients_engagement_mode

Revision ID: 20260414_release_a_clients
Revises: 7f1c9b2d4a10
Create Date: 2026-04-14
"""

from alembic import op
import sqlalchemy as sa


revision = "20260414_release_a_clients"
down_revision = "7f1c9b2d4a10"
branch_labels = None
depends_on = None


def _has_column(table_name: str, column_name: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return column_name in [c["name"] for c in inspector.get_columns(table_name)]


def upgrade():
    # On the original production database this column was added out-of-band,
    # outside of tracked migration history. On a fresh database (new env,
    # new backend such as Postgres) it does not exist yet, so create it
    # defensively here instead of assuming it's already present.
    if not _has_column("clients", "engagement_mode"):
        op.add_column(
            "clients",
            sa.Column(
                "engagement_mode",
                sa.String(length=30),
                nullable=False,
                server_default="internal_managed",
            ),
        )

    # Make partner_id nullable in a SQLite-safe way
    with op.batch_alter_table("clients") as batch_op:
        batch_op.alter_column(
            "partner_id",
            existing_type=sa.Integer(),
            nullable=True,
        )

    # Remove server default from engagement_mode if it exists
    with op.batch_alter_table("clients") as batch_op:
        batch_op.alter_column(
            "engagement_mode",
            existing_type=sa.String(length=30),
            server_default=None,
        )


def downgrade():
    # Revert partner_id back to NOT NULL
    with op.batch_alter_table("clients") as batch_op:
        batch_op.alter_column(
            "partner_id",
            existing_type=sa.Integer(),
            nullable=False,
        )

    # Drop engagement_mode
    with op.batch_alter_table("clients") as batch_op:
        batch_op.drop_column("engagement_mode")