"""device table (无障碍保护存活检测 + 极光推送)

Revision ID: device_liveness_table
Revises: ceb286289426
Create Date: 2026-06-15 12:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'device_liveness_table'
down_revision: Union[str, Sequence[str], None] = 'ceb286289426'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        'device_liveness',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('user_id', sa.Integer(), nullable=False),
        sa.Column('device_id', sa.String(length=128), nullable=False),
        sa.Column('registration_id', sa.String(length=64), nullable=True),
        sa.Column('platform', sa.String(length=16), nullable=False),
        sa.Column('app_version', sa.String(length=32), nullable=True),
        sa.Column('ever_protected', sa.Boolean(), nullable=False),
        sa.Column('last_heartbeat_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('last_report_protection_on', sa.Boolean(), nullable=False),
        sa.Column('liveness_state', sa.String(length=16), nullable=False),
        sa.Column('notified_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
        sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('user_id', 'device_id', name='uq_device_liveness_user_device'),
    )
    with op.batch_alter_table('device_liveness', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_device_liveness_user_id'), ['user_id'], unique=False)
        batch_op.create_index(batch_op.f('ix_device_liveness_device_id'), ['device_id'], unique=False)
        batch_op.create_index(batch_op.f('ix_device_liveness_last_heartbeat_at'), ['last_heartbeat_at'], unique=False)


def downgrade() -> None:
    with op.batch_alter_table('device_liveness', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_device_liveness_last_heartbeat_at'))
        batch_op.drop_index(batch_op.f('ix_device_liveness_device_id'))
        batch_op.drop_index(batch_op.f('ix_device_liveness_user_id'))

    op.drop_table('device_liveness')
