"""Normalise les rôles utilisateurs.

Revision ID: a2b6c7d8e9f0
Revises: f1a5b6c7d8e9
Create Date: 2026-08-14
"""

from alembic import op
import sqlalchemy as sa


revision = "a2b6c7d8e9f0"
down_revision = "f1a5b6c7d8e9"
branch_labels = None
depends_on = None


def upgrade():
    op.alter_column(
        "users", "role", existing_type=sa.String(length=20),
        type_=sa.String(length=32), nullable=False, server_default="demandeur",
    )
    op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin'")
    op.execute("UPDATE users SET role = 'responsable_gmao' WHERE role IN ('chef', 'responsable')")
    op.execute("UPDATE users SET role = 'technicien' WHERE role IN ('tech', 'technician')")
    op.execute("UPDATE users SET role = 'demandeur' WHERE role IN ('user', 'requester') OR role IS NULL OR role = ''")
    op.execute("UPDATE users SET role = 'lecture' WHERE role = 'viewer'")


def downgrade():
    op.execute("UPDATE users SET role = 'chef' WHERE role = 'responsable_gmao'")
    op.execute("UPDATE users SET role = 'tech' WHERE role IN ('technicien', 'assistant_prevention')")
    op.execute("UPDATE users SET role = 'user' WHERE role = 'demandeur'")
    op.execute("UPDATE users SET role = 'viewer' WHERE role = 'lecture'")
    op.alter_column(
        "users", "role", existing_type=sa.String(length=32),
        type_=sa.String(length=20), nullable=True, server_default="user",
    )
