"""Ajustes de sesión: país ISO-3 en accounts, giro "otro" y formas de pago SAT a 2 dígitos

Revision ID: d3e4f5a6b7c8
Revises: c2d3e4f5a6b7
Create Date: 2026-08-04 01:00:00.000000

- crm.accounts.country String(2)→String(3) (ISO alfa-3, alineado a catálogo pais).
- crm.accounts.industry_other (especificar cuando el giro es "otro").
- Normaliza formas de pago SAT de 1 dígito a 2 (01, 02, …) en el catálogo y en
  los valores guardados en accounts/suppliers; y país 'MX'→'MEX'.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "d3e4f5a6b7c8"
down_revision: Union[str, None] = "c2d3e4f5a6b7"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

SCHEMA = "crm"


def upgrade() -> None:
    # País a ISO alfa-3 en accounts (addresses ya es String(3)).
    # Primero se amplía la columna; luego se normaliza el dato (evita truncamiento).
    op.alter_column(
        "accounts", "country", schema=SCHEMA,
        existing_type=sa.String(length=2), type_=sa.String(length=3),
        existing_nullable=True, server_default=sa.text("'MEX'"),
    )
    op.execute("UPDATE crm.accounts SET country = 'MEX' WHERE country = 'MX'")
    op.execute("UPDATE crm.addresses SET country = 'MEX' WHERE country = 'MX'")
    # Giro "otro" — campo para especificar
    op.add_column("accounts", sa.Column("industry_other", sa.String(length=120), nullable=True), schema=SCHEMA)

    # Formas de pago SAT: 1 dígito → 2 dígitos (catálogo + valores guardados)
    op.execute(
        "UPDATE crm.catalog_items SET code = lpad(code, 2, '0') "
        "WHERE catalog = 'forma_pago' AND char_length(code) = 1"
    )
    op.execute("UPDATE crm.accounts SET payment_form = lpad(payment_form, 2, '0') WHERE char_length(payment_form) = 1")
    op.execute("UPDATE crm.suppliers SET payment_form = lpad(payment_form, 2, '0') WHERE char_length(payment_form) = 1")


def downgrade() -> None:
    op.drop_column("accounts", "industry_other", schema=SCHEMA)
    # Regresar país a String(2) sin truncar filas existentes
    op.execute("UPDATE crm.accounts SET country = 'MX' WHERE country = 'MEX'")
    op.alter_column(
        "accounts", "country", schema=SCHEMA,
        existing_type=sa.String(length=3), type_=sa.String(length=2),
        existing_nullable=True, server_default=sa.text("'MX'"),
    )
    # La normalización de formas de pago no se revierte (evita romper códigos multi-dígito).
