"""user.invite_code + invite_relation table

Revision ID: invite_code_and_relation
Revises: 11a1d08c6f55
Create Date: 2026-06-08 00:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    # user 加邀请码列(唯一索引;nullable 允许多个 NULL=未生成的用户)
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.add_column(sa.Column('invite_code', sa.String(length=16), nullable=True))
        batch_op.create_index('ix_user_invite_code', ['invite_code'], unique=True)

    # 邀请关系表
    op.create_table(
        'invite_relation',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('inviter_user_id', sa.Integer(), nullable=False),
        sa.Column('invitee_user_id', sa.Integer(), nullable=False),
        sa.Column('channel', sa.String(length=16), nullable=False, server_default='clipboard'),
        sa.Column('status', sa.String(length=16), nullable=False, server_default='effective'),
        sa.Column('inviter_coin', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('invitee_coin', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(['inviter_user_id'], ['user.id']),
        sa.ForeignKeyConstraint(['invitee_user_id'], ['user.id']),
        sa.PrimaryKeyConstraint('id'),
    )
    op.create_index('ix_invite_relation_inviter_user_id', 'invite_relation', ['inviter_user_id'])
    op.create_index('ix_invite_relation_invitee_user_id', 'invite_relation', ['invitee_user_id'], unique=True)
    op.create_index('ix_invite_relation_created_at', 'invite_relation', ['created_at'])


def downgrade() -> None:
    op.drop_index('ix_invite_relation_created_at', table_name='invite_relation')
    op.drop_index('ix_invite_relation_invitee_user_id', table_name='invite_relation')
    op.drop_index('ix_invite_relation_inviter_user_id', table_name='invite_relation')
    op.drop_table('invite_relation')
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_index('ix_user_invite_code')
        batch_op.drop_column('invite_code')
