"""invite_fingerprint table (任务 3 指纹归因兜底)

Revision ID: invite_fingerprint_table
Revises: 0cf18d590b1d
Create Date: 2026-06-08 14:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    # 邀请指纹归因表:落地页访问时记一行,登录后剪贴板没拿到邀请码时反查
    op.create_table(
        'invite_fingerprint',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('inviter_user_id', sa.Integer(), nullable=False),
        sa.Column('ip', sa.String(length=64), nullable=False),
        sa.Column('device_model', sa.String(length=64), nullable=False, server_default=''),
        sa.Column('screen', sa.String(length=32), nullable=False, server_default=''),
        sa.Column('user_agent', sa.Text(), nullable=False, server_default=''),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(['inviter_user_id'], ['user.id']),
        sa.PrimaryKeyConstraint('id'),
    )
    # 反查主索引:(ip, screen, device_model, created_at)
    # /bind 兜底分支 WHERE ip=? AND screen=? AND device_model=? AND created_at > now - 7d
    # ORDER BY created_at DESC LIMIT 1 — SQLite/PG 优化器都能反向扫该索引
    op.create_index(
        'ix_invite_fp_match',
        'invite_fingerprint',
        ['ip', 'screen', 'device_model', 'created_at'],
    )
    # 兜底/统计索引:按 inviter 看"这个邀请人的落地页被谁访问过"
    op.create_index('ix_invite_fp_inviter', 'invite_fingerprint', ['inviter_user_id'])


def downgrade() -> None:
    op.drop_index('ix_invite_fp_inviter', table_name='invite_fingerprint')
    op.drop_index('ix_invite_fp_match', table_name='invite_fingerprint')
    op.drop_table('invite_fingerprint')
