"""Ajouter les actions granulaires au catalogue RBAC.
Revision ID: 9c17d8e9f0a1
Revises: 9b06c7d8e9f0
"""
from alembic import op
import sqlalchemy as sa
from app_new.core.authorization import GRANULAR_PERMISSION_CODES
revision = "9c17d8e9f0a1"
down_revision = "9b06c7d8e9f0"
branch_labels = None
depends_on = None
def upgrade():
    bind = op.get_bind()
    for code in sorted(GRANULAR_PERMISSION_CODES):
        bits = code.split(".", 1)
        module = bits[0]
        action = bits[1] if len(bits) > 1 else "manage"
        bind.execute(sa.text("INSERT INTO permissions (code,name,module,action,description,is_active) SELECT :code,:name,:module,:action,:description,1 FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code=:code)"), {"code": code, "name": f"{module.title()} — {action}", "module": module, "action": action, "description": "Action granulaire configurable"})
def downgrade():
    bind = op.get_bind()
    for code in sorted(GRANULAR_PERMISSION_CODES):
        bind.execute(sa.text("DELETE FROM permissions WHERE code=:code"), {"code": code})

