"""add user audit fields

Revision ID: 4f0b8a3e5c20
Revises: 21226a449037
Create Date: 2025-12-29 00:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = '4f0b8a3e5c20'
down_revision: Union[str, None] = '21226a449037'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    op.add_column('users', sa.Column('last_login_at', sa.TIMESTAMP(timezone=True), nullable=True))
    op.add_column('users', sa.Column('last_password_change_at', sa.TIMESTAMP(timezone=True), nullable=True))
    op.add_column('users', sa.Column('last_failed_login_at', sa.TIMESTAMP(timezone=True), nullable=True))
    op.add_column(
        'users',
        sa.Column('failed_login_attempts', sa.Integer(), nullable=False, server_default='0')
    )
    op.add_column('users', sa.Column('locked_until', sa.TIMESTAMP(timezone=True), nullable=True))
    op.add_column('users', sa.Column('deactivated_at', sa.TIMESTAMP(timezone=True), nullable=True))
    op.add_column('users', sa.Column('deactivated_by', sa.Integer(), nullable=True))
    op.create_foreign_key(
        'fk_users_deactivated_by_users',
        'users',
        'users',
        ['deactivated_by'],
        ['id'],
        ondelete='SET NULL',
    )
    # Optional: keep server_default for failed_login_attempts; remove if you prefer no default after backfill


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_constraint('fk_users_deactivated_by_users', 'users', type_='foreignkey')
    op.drop_column('users', 'deactivated_by')
    op.drop_column('users', 'deactivated_at')
    op.drop_column('users', 'locked_until')
    op.drop_column('users', 'failed_login_attempts')
    op.drop_column('users', 'last_failed_login_at')
    op.drop_column('users', 'last_password_change_at')
    op.drop_column('users', 'last_login_at')
