/**
 * 系统管理功能数据库迁移
 * @file 20250118000000_system_management.js
 * @description 创建系统配置和菜单权限管理表
 */

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 创建系统配置表
      await queryInterface.createTable('system_configs', {
        id: {
          type: Sequelize.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          comment: '配置ID'
        },
        config_key: {
          type: Sequelize.STRING(100),
          allowNull: false,
          unique: true,
          comment: '配置键名'
        },
        config_value: {
          type: Sequelize.TEXT,
          allowNull: true,
          comment: '配置值'
        },
        config_type: {
          type: Sequelize.ENUM('string', 'number', 'boolean', 'json', 'array'),
          allowNull: false,
          defaultValue: 'string',
          comment: '配置类型'
        },
        category: {
          type: Sequelize.STRING(50),
          allowNull: false,
          defaultValue: 'general',
          comment: '配置分类'
        },
        description: {
          type: Sequelize.STRING(255),
          allowNull: true,
          comment: '配置描述'
        },
        is_public: {
          type: Sequelize.BOOLEAN,
          allowNull: false,
          defaultValue: false,
          comment: '是否公开（前端可访问）'
        },
        is_editable: {
          type: Sequelize.BOOLEAN,
          allowNull: false,
          defaultValue: true,
          comment: '是否可编辑'
        },
        sort_order: {
          type: Sequelize.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '排序顺序'
        },
        updated_by: {
          type: Sequelize.INTEGER,
          allowNull: true,
          comment: '最后更新人ID'
        },
        created_at: {
          type: Sequelize.DATE,
          allowNull: false,
          defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
        },
        updated_at: {
          type: Sequelize.DATE,
          allowNull: false,
          defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
        }
      }, {
        transaction,
        comment: '系统配置表'
      });

      // 创建菜单权限表
      await queryInterface.createTable('menu_permissions', {
        id: {
          type: Sequelize.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          comment: '权限ID'
        },
        menu_key: {
          type: Sequelize.STRING(100),
          allowNull: false,
          unique: true,
          comment: '菜单标识'
        },
        menu_name: {
          type: Sequelize.STRING(100),
          allowNull: false,
          comment: '菜单名称'
        },
        menu_path: {
          type: Sequelize.STRING(200),
          allowNull: true,
          comment: '菜单路径'
        },
        parent_id: {
          type: Sequelize.INTEGER,
          allowNull: true,
          comment: '父菜单ID'
        },
        menu_type: {
          type: Sequelize.ENUM('page', 'button', 'api'),
          allowNull: false,
          defaultValue: 'page',
          comment: '菜单类型'
        },
        required_roles: {
          type: Sequelize.TEXT,
          allowNull: true,
          comment: '所需角色（JSON数组）'
        },
        required_permissions: {
          type: Sequelize.TEXT,
          allowNull: true,
          comment: '所需权限（JSON数组）'
        },
        icon: {
          type: Sequelize.STRING(50),
          allowNull: true,
          comment: '菜单图标'
        },
        sort_order: {
          type: Sequelize.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '排序顺序'
        },
        is_visible: {
          type: Sequelize.BOOLEAN,
          allowNull: false,
          defaultValue: true,
          comment: '是否可见'
        },
        is_enabled: {
          type: Sequelize.BOOLEAN,
          allowNull: false,
          defaultValue: true,
          comment: '是否启用'
        },
        description: {
          type: Sequelize.STRING(255),
          allowNull: true,
          comment: '菜单描述'
        },
        created_at: {
          type: Sequelize.DATE,
          allowNull: false,
          defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
        },
        updated_at: {
          type: Sequelize.DATE,
          allowNull: false,
          defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
        }
      }, {
        transaction,
        comment: '菜单权限表'
      });

      // 添加索引
      await queryInterface.addIndex('system_configs', ['config_key'], {
        unique: true,
        transaction
      });
      
      await queryInterface.addIndex('system_configs', ['category'], {
        transaction
      });
      
      await queryInterface.addIndex('system_configs', ['is_public'], {
        transaction
      });
      
      await queryInterface.addIndex('menu_permissions', ['menu_key'], {
        unique: true,
        transaction
      });
      
      await queryInterface.addIndex('menu_permissions', ['parent_id'], {
        transaction
      });
      
      await queryInterface.addIndex('menu_permissions', ['menu_type'], {
        transaction
      });
      
      await queryInterface.addIndex('menu_permissions', ['sort_order'], {
        transaction
      });

      // 添加外键约束
      await queryInterface.addConstraint('menu_permissions', {
        fields: ['parent_id'],
        type: 'foreign key',
        name: 'fk_menu_permissions_parent_id',
        references: {
          table: 'menu_permissions',
          field: 'id'
        },
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE',
        transaction
      });

      await transaction.commit();
      console.log('系统管理表创建成功');
    } catch (error) {
      await transaction.rollback();
      console.error('系统管理表创建失败:', error);
      throw error;
    }
  },

  down: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 删除外键约束
      await queryInterface.removeConstraint('menu_permissions', 'fk_menu_permissions_parent_id', {
        transaction
      });

      // 删除表
      await queryInterface.dropTable('menu_permissions', { transaction });
      await queryInterface.dropTable('system_configs', { transaction });

      await transaction.commit();
      console.log('系统管理表删除成功');
    } catch (error) {
      await transaction.rollback();
      console.error('系统管理表删除失败:', error);
      throw error;
    }
  }
};
