/**
 * 角色模型
 * @file Role.js
 * @description 银行系统角色模型定义
 */
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');
const { sequelize } = require('../config/database');

class Role extends BaseModel {
  /**
   * 获取角色权限
   * @returns {Promise<Array>} 权限列表
   */
  async getPermissions() {
    try {
      const { Permission } = require('./index');
      const rolePermissions = await this.getPermissions();
      return rolePermissions.map(rp => rp.Permission);
    } catch (error) {
      console.error('获取角色权限失败:', error);
      return [];
    }
  }

  /**
   * 检查角色是否具有指定权限
   * @param {String|Array} permissionName 权限名称或权限名称数组
   * @returns {Promise<Boolean>} 检查结果
   */
  async hasPermission(permissionName) {
    const permissions = await this.getPermissions();
    const permissionNames = permissions.map(permission => permission.name);
    
    if (Array.isArray(permissionName)) {
      return permissionName.some(name => permissionNames.includes(name));
    }
    
    return permissionNames.includes(permissionName);
  }

  /**
   * 获取角色用户列表
   * @returns {Promise<Array>} 用户列表
   */
  async getUsers() {
    try {
      const { User } = require('./index');
      return await User.findAll({
        where: { role_id: this.id }
      });
    } catch (error) {
      console.error('获取角色用户失败:', error);
      return [];
    }
  }
}

// 初始化Role模型
Role.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    validate: {
      len: [2, 50]
    }
  },
  display_name: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  level: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
    comment: '角色级别，数字越大权限越高'
  },
  is_system: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否为系统角色'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  },
  created_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  }
}, {
  sequelize,
  tableName: 'bank_roles',
  modelName: 'Role',
  timestamps: true,
  underscored: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

module.exports = Role;