"""add_platform_role_replace_is_superuser

数据迁移：is_superuser=True → platform_role='platform_owner'
         is_superuser=False → platform_role=NULL

Revision ID: b9b08e00f488
Revises: 5bb112b00290
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa


revision: str = 'b9b08e00f488'
down_revision: Union[str, None] = '5bb112b00290'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # 1. 新增 platform_role 列
    op.add_column('users', sa.Column('platform_role', sa.String(length=30), nullable=True))

    # 2. 数据迁移：is_superuser=True → platform_owner
    op.execute(
        "UPDATE users SET platform_role = 'platform_owner' WHERE is_superuser = TRUE"
    )

    # 3. 删除旧列
    op.drop_column('users', 'is_superuser')

    # 4. 新增 audit_logs 表
    op.create_table(
        'audit_logs',
        sa.Column('id', sa.Uuid(), nullable=False),
        sa.Column('actor_id', sa.Uuid(), nullable=False),
        sa.Column('tenant_id', sa.Uuid(), nullable=True),
        sa.Column('action', sa.String(length=50), nullable=False),
        sa.Column('target_type', sa.String(length=50), nullable=True),
        sa.Column('target_id', sa.String(length=100), nullable=True),
        sa.Column('detail', sa.Text(), nullable=True),
        sa.Column('ip_address', sa.String(length=45), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.PrimaryKeyConstraint('id'),
    )
    op.create_index(op.f('ix_audit_actor'), 'audit_logs', ['actor_id', 'created_at'])
    op.create_index(op.f('ix_audit_action'), 'audit_logs', ['action', 'created_at'])


def downgrade() -> None:
    # 回滚 audit_logs 表
    op.drop_index(op.f('ix_audit_action'), table_name='audit_logs')
    op.drop_index(op.f('ix_audit_actor'), table_name='audit_logs')
    op.drop_table('audit_logs')

    # 回滚 users 变更
    op.add_column('users', sa.Column('is_superuser', sa.BOOLEAN(), server_default=sa.text('false'), nullable=False))
    op.execute(
        "UPDATE users SET is_superuser = TRUE WHERE platform_role IS NOT NULL"
    )
    op.drop_column('users', 'platform_role')
