"""Rattacher les tâches administratives à un technicien."""

from alembic import op
import sqlalchemy as sa


revision = "g2b3c4d5e6f7"
down_revision = "g1a2b3c4d5e6"
branch_labels = None
depends_on = None


def _columns(bind):
    return {item["name"] for item in sa.inspect(bind).get_columns("admin_tasks")}


def upgrade():
    bind = op.get_bind()
    if "user_id" not in _columns(bind):
        op.add_column("admin_tasks", sa.Column("user_id", sa.Integer(), nullable=True))
        op.create_index("ix_admin_tasks_user_id", "admin_tasks", ["user_id"])
        op.create_foreign_key(
            "fk_admin_tasks_user_id_users", "admin_tasks", "users", ["user_id"], ["id"]
        )


def downgrade():
    bind = op.get_bind()
    if "user_id" in _columns(bind):
        inspector = sa.inspect(bind)
        if "ix_admin_tasks_user_id" in {item["name"] for item in inspector.get_indexes("admin_tasks")}:
            op.drop_index("ix_admin_tasks_user_id", table_name="admin_tasks")
        if "fk_admin_tasks_user_id_users" in {item["name"] for item in inspector.get_foreign_keys("admin_tasks")}:
            op.drop_constraint("fk_admin_tasks_user_id_users", "admin_tasks", type_="foreignkey")
        op.drop_column("admin_tasks", "user_id")
