"""ampliar crm.addresses.country a 3 (país ISO alfa-3 del catálogo)

Revision ID: e7f8a9b0c1d2
Revises: e6f7a8b9c0d1
Create Date: 2026-07-22 00:30:00.000000

El catálogo de País usa códigos ISO 3166 alfa-3 (MEX, USA, …). La columna
addresses.country era String(2); se amplía a String(3) para almacenarlos.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "e7f8a9b0c1d2"
down_revision: Union[str, None] = "e6f7a8b9c0d1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

SCHEMA = "crm"


def upgrade() -> None:
    op.alter_column(
        "addresses", "country",
        type_=sa.String(length=3),
        existing_type=sa.String(length=2),
        existing_nullable=True,
        server_default=sa.text("'MEX'"),
        schema=SCHEMA,
    )


def downgrade() -> None:
    # Trunca a 2 chars por si hay códigos alfa-3 guardados (rollback de dev).
    op.execute("UPDATE crm.addresses SET country = left(country, 2) WHERE length(country) > 2")
    op.alter_column(
        "addresses", "country",
        type_=sa.String(length=2),
        existing_type=sa.String(length=3),
        existing_nullable=True,
        server_default=sa.text("'MX'"),
        schema=SCHEMA,
    )
