'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    // 创建菜单权限关联表
    await queryInterface.createTable('menu_permissions', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        comment: '关联ID'
      },
      menu_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '菜单ID',
        references: {
          model: 'menus',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      permission_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '权限ID',
        references: {
          model: 'permissions',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      required: {
        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('menu_permissions', ['menu_id', 'permission_id'], {
      name: 'uk_menu_permission',
      unique: true
    });
    
    // 创建普通索引
    await queryInterface.addIndex('menu_permissions', ['menu_id'], {
      name: 'idx_menu_permissions_menu_id'
    });
    await queryInterface.addIndex('menu_permissions', ['permission_id'], {
      name: 'idx_menu_permissions_permission_id'
    });
  },

  async down(queryInterface, Sequelize) {
    // 删除索引
    await queryInterface.removeIndex('menu_permissions', 'uk_menu_permission');
    await queryInterface.removeIndex('menu_permissions', 'idx_menu_permissions_menu_id');
    await queryInterface.removeIndex('menu_permissions', 'idx_menu_permissions_permission_id');
    
    // 删除表
    await queryInterface.dropTable('menu_permissions');
  }
};