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

const Menu = sequelize.define('Menu', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    validate: {
      len: [2, 50]
    }
  },
  key: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    validate: {
      len: [2, 50]
    }
  },
  path: {
    type: DataTypes.STRING(100),
    allowNull: false,
    validate: {
      len: [1, 100]
    }
  },
  icon: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  parent_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'menus',
      key: 'id'
    },
    defaultValue: null
  },
  component: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  order: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  },
  show: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  }
}, {
  tableName: 'menus',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['key'] },
    { fields: ['parent_id'] },
    { fields: ['status'] },
    { fields: ['order'] }
  ]
});

// 设置自关联
Menu.hasMany(Menu, {
  as: 'children',
  foreignKey: 'parent_id'
});

Menu.belongsTo(Menu, {
  as: 'parent',
  foreignKey: 'parent_id'
});

module.exports = Menu;