const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Permission = sequelize.define('Permission', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
    comment: '权限ID'
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '权限名称',
    validate: {
      len: [2, 100]
    }
  },
  code: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true,
    comment: '权限代码',
    validate: {
      len: [2, 100],
      is: /^[a-zA-Z0-9_:]+$/  // 只允许字母、数字、下划线和冒号
    }
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '权限描述'
  },
  module: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '所属模块',
    validate: {
      len: [2, 50]
    }
  },
  type: {
    type: DataTypes.ENUM('menu', 'operation'),
    allowNull: false,
    defaultValue: 'operation',
    comment: '权限类型：menu-菜单权限，operation-操作权限'
  },
  parent_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '父权限ID'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    allowNull: false,
    defaultValue: 'active',
    comment: '状态'
  },
  sort_order: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '排序'
  }
}, {
  tableName: 'permissions',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['code'], unique: true },
    { fields: ['module'] },
    { fields: ['type'] },
    { fields: ['parent_id'] },
    { fields: ['status'] }
  ]
});

// 定义自关联关系
Permission.hasMany(Permission, { 
  as: 'children', 
  foreignKey: 'parent_id',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});

Permission.belongsTo(Permission, { 
  as: 'parent', 
  foreignKey: 'parent_id',
  onDelete: 'SET NULL',
  onUpdate: 'CASCADE'
});

module.exports = Permission;

