"""add administrator permission management

Revision ID: 0031_admin_permissions
Revises: 0030_sso_chat_source
"""

from alembic import op
import sqlalchemy as sa

revision = "0031_admin_permissions"
down_revision = "0030_sso_chat_source"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # MySQL does not permit a DEFAULT on TEXT on all supported versions.
    op.add_column("sys_role", sa.Column("permissions", sa.Text(), nullable=True))
    op.execute("UPDATE sys_role SET permissions = '[]' WHERE permissions IS NULL")
    op.alter_column("sys_role", "permissions", existing_type=sa.Text(), nullable=False)
    op.add_column("sys_admin", sa.Column("must_change_password", sa.Integer(), nullable=False, server_default="1"))
    op.add_column("sys_admin", sa.Column("is_super_admin", sa.Integer(), nullable=False, server_default="0"))
    # Existing installations have one bootstrap administrator. Preserve it as the immutable super administrator.
    op.execute("UPDATE sys_admin SET is_super_admin = 1, must_change_password = 0 WHERE id = (SELECT id FROM (SELECT MIN(id) AS id FROM sys_admin) AS first_admin)")


def downgrade() -> None:
    op.drop_column("sys_admin", "is_super_admin")
    op.drop_column("sys_admin", "must_change_password")
    op.drop_column("sys_role", "permissions")
