"""添加RBAC权限管理

Revision ID: 003_add_rbac
Revises: 002_add_template_market
Create Date: 2024-01-17

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '003_add_rbac'
down_revision = '002_add_template_market'
branch_labels = None
depends_on = None


def upgrade():
    # 创建角色表
    op.create_table(
        'roles',
        sa.Column('id', sa.CHAR(length=36), nullable=False, comment='角色ID'),
        sa.Column('name', sa.String(length=50), nullable=False, comment='角色名称'),
        sa.Column('description', sa.String(length=255), nullable=True, comment='角色描述'),
        sa.Column('is_system', sa.Boolean(), nullable=True, server_default='0', comment='是否系统角色（不可删除）'),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP'), comment='创建时间'),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间'),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name')
    )
    
    # 创建权限表
    op.create_table(
        'permissions',
        sa.Column('id', sa.CHAR(length=36), nullable=False, comment='权限ID'),
        sa.Column('name', sa.String(length=100), nullable=False, comment='权限名称'),
        sa.Column('code', sa.String(length=100), nullable=False, comment='权限代码（如：workflow:create）'),
        sa.Column('resource', sa.String(length=50), nullable=False, comment='资源类型（如：workflow、agent、execution）'),
        sa.Column('action', sa.String(length=50), nullable=False, comment='操作类型（如：create、read、update、delete、execute）'),
        sa.Column('description', sa.String(length=255), nullable=True, comment='权限描述'),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP'), comment='创建时间'),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间'),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('code'),
        sa.UniqueConstraint('name')
    )
    
    # 创建用户角色关联表
    op.create_table(
        'user_roles',
        sa.Column('user_id', sa.CHAR(length=36), nullable=False),
        sa.Column('role_id', sa.CHAR(length=36), nullable=False),
        sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('user_id', 'role_id')
    )
    
    # 创建角色权限关联表
    op.create_table(
        'role_permissions',
        sa.Column('role_id', sa.CHAR(length=36), nullable=False),
        sa.Column('permission_id', sa.CHAR(length=36), nullable=False),
        sa.ForeignKeyConstraint(['permission_id'], ['permissions.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('role_id', 'permission_id')
    )
    
    # 创建工作流权限表
    op.create_table(
        'workflow_permissions',
        sa.Column('id', sa.CHAR(length=36), nullable=False, comment='权限ID'),
        sa.Column('workflow_id', sa.CHAR(length=36), nullable=False, comment='工作流ID'),
        sa.Column('user_id', sa.CHAR(length=36), nullable=True, comment='用户ID（null表示所有用户）'),
        sa.Column('role_id', sa.CHAR(length=36), nullable=True, comment='角色ID（null表示所有角色）'),
        sa.Column('permission_type', sa.String(length=20), nullable=False, comment='权限类型：read/write/execute/share'),
        sa.Column('granted_by', sa.CHAR(length=36), nullable=False, comment='授权人ID'),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP'), comment='创建时间'),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间'),
        sa.ForeignKeyConstraint(['granted_by'], ['users.id']),
        sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['workflow_id'], ['workflows.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    
    # 创建Agent权限表
    op.create_table(
        'agent_permissions',
        sa.Column('id', sa.CHAR(length=36), nullable=False, comment='权限ID'),
        sa.Column('agent_id', sa.CHAR(length=36), nullable=False, comment='Agent ID'),
        sa.Column('user_id', sa.CHAR(length=36), nullable=True, comment='用户ID（null表示所有用户）'),
        sa.Column('role_id', sa.CHAR(length=36), nullable=True, comment='角色ID（null表示所有角色）'),
        sa.Column('permission_type', sa.String(length=20), nullable=False, comment='权限类型：read/write/execute/deploy'),
        sa.Column('granted_by', sa.CHAR(length=36), nullable=False, comment='授权人ID'),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP'), comment='创建时间'),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间'),
        sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['granted_by'], ['users.id']),
        sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    
    # 创建索引
    op.create_index('idx_workflow_permissions_workflow', 'workflow_permissions', ['workflow_id'])
    op.create_index('idx_workflow_permissions_user', 'workflow_permissions', ['user_id'])
    op.create_index('idx_workflow_permissions_role', 'workflow_permissions', ['role_id'])
    op.create_index('idx_agent_permissions_agent', 'agent_permissions', ['agent_id'])
    op.create_index('idx_agent_permissions_user', 'agent_permissions', ['user_id'])
    op.create_index('idx_agent_permissions_role', 'agent_permissions', ['role_id'])


def downgrade():
    op.drop_index('idx_agent_permissions_role', table_name='agent_permissions')
    op.drop_index('idx_agent_permissions_user', table_name='agent_permissions')
    op.drop_index('idx_agent_permissions_agent', table_name='agent_permissions')
    op.drop_index('idx_workflow_permissions_role', table_name='workflow_permissions')
    op.drop_index('idx_workflow_permissions_user', table_name='workflow_permissions')
    op.drop_index('idx_workflow_permissions_workflow', table_name='workflow_permissions')
    op.drop_table('agent_permissions')
    op.drop_table('workflow_permissions')
    op.drop_table('role_permissions')
    op.drop_table('user_roles')
    op.drop_table('permissions')
    op.drop_table('roles')
