"""caldav name_template + users.kuerzel

Revision ID: 0012
Revises: 0011_caldav_name_format
Create Date: 2026-03-28
"""
from alembic import op
import sqlalchemy as sa

revision = '0012_caldav_template_and_kuerzel'
down_revision = '0011_caldav_name_format'
branch_labels = None
depends_on = None

# Mapping alter Festwert → neues Template
_MIGRATION_MAP = {
    'full':      '$vorname $nachname – $typ',
    'short':     '$vorname_short. $nachname – $typ',
    'initials':  '$kuerzel – $typ',
    'type_only': '$typ',
}
_DEFAULT = '$vorname $nachname – $typ'


def upgrade() -> None:
    # 1. Neue Spalte name_template hinzufügen
    op.add_column('caldav_company_configs', sa.Column(
        'name_template', sa.Text(), nullable=False,
        server_default=_DEFAULT,
    ))

    # 2. Bestehende Werte aus name_format migrieren
    for old_val, new_val in _MIGRATION_MAP.items():
        op.execute(
            f"UPDATE caldav_company_configs "
            f"SET name_template = '{new_val}' "
            f"WHERE name_format = '{old_val}'"
        )

    # 3. Alte Spalte entfernen
    op.drop_column('caldav_company_configs', 'name_format')

    # 4. Kürzel-Spalte zu users hinzufügen
    op.add_column('users', sa.Column(
        'kuerzel', sa.String(20), nullable=True
    ))


def downgrade() -> None:
    op.add_column('caldav_company_configs', sa.Column(
        'name_format', sa.String(20), nullable=False, server_default='full'
    ))
    op.drop_column('caldav_company_configs', 'name_template')
    op.drop_column('users', 'kuerzel')
