"""User forced-password-change flag (users.mustchangepassword)

Adds a boolean users.mustchangepassword column (default false). An admin who
creates a user sets it true so the user is forced through a password change on
first login; changing the password clears it.

Idempotent guard so it is safe on a partially-migrated box; real downgrade.

Revision ID: 7d23_user_mustchangepassword
Revises: 7d22_apitokens_scopes
Create Date: 2026-07-12

"""
from alembic import op
import sqlalchemy as sa


revision = '7d23_user_mustchangepassword'
down_revision = '7d22_apitokens_scopes'
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'users' not in insp.get_table_names():
        return
    columns = {c['name'] for c in insp.get_columns('users')}
    if 'mustchangepassword' in columns:
        return

    op.add_column(
        'users',
        sa.Column('mustchangepassword', sa.Boolean(),
                  nullable=False, server_default=sa.false()))


def downgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'users' not in insp.get_table_names():
        return
    columns = {c['name'] for c in insp.get_columns('users')}
    if 'mustchangepassword' not in columns:
        return

    op.drop_column('users', 'mustchangepassword')
