'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    // 创建角色权限关联表
    await queryInterface.createTable('role_permissions', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        comment: '关联ID'
      },
      role_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '角色ID',
        references: {
          model: 'roles',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      permission_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '权限ID',
        references: {
          model: 'permissions',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      granted: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        comment: '是否授权'
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
        comment: '创建时间'
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
        comment: '更新时间'
      }
    }, {
      comment: '角色权限关联表'
    });

    // 创建唯一索引
    await queryInterface.addIndex('role_permissions', ['role_id', 'permission_id'], {
      name: 'uk_role_permission',
      unique: true
    });
    
    // 创建普通索引
    await queryInterface.addIndex('role_permissions', ['role_id'], {
      name: 'idx_role_permissions_role_id'
    });
    await queryInterface.addIndex('role_permissions', ['permission_id'], {
      name: 'idx_role_permissions_permission_id'
    });
  },

  async down(queryInterface, Sequelize) {
    // 删除索引
    await queryInterface.removeIndex('role_permissions', 'uk_role_permission');
    await queryInterface.removeIndex('role_permissions', 'idx_role_permissions_role_id');
    await queryInterface.removeIndex('role_permissions', 'idx_role_permissions_permission_id');
    
    // 删除表
    await queryInterface.dropTable('role_permissions');
  }
};