module.exports = (sequelize, DataTypes) => {
  const Permission = sequelize.define('Permission', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    permission_code: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true
    },
    permission_name: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    module: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: 'Module name (e.g., MASTER, PURCHASE, SALES, PRODUCTION, FINANCE)'
    },
    resource: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'Resource name (e.g., material, purchase_order)'
    },
    action: {
      type: DataTypes.ENUM('CREATE', 'READ', 'UPDATE', 'DELETE', 'APPROVE', 'REJECT', 'EXPORT', 'IMPORT', 'ALL'),
      allowNull: false,
      comment: 'Legacy field - kept for backward compatibility'
    },
    operation: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: 'Operation name (e.g., CREATE, EDIT, APPROVE, VIEW, PRINT, EXPORT, CLOSE, REOPEN, START, PAUSE, RESUME, CANCEL, UPLOAD, DOWNLOAD)'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    is_system_permission: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    }
  }, {
    tableName: 'permission',
    indexes: [
      {
        unique: true,
        fields: ['permission_code']
      },
      {
        fields: ['module']
      },
      {
        fields: ['resource']
      },
      {
        fields: ['status']
      }
    ]
  });

  Permission.associate = function(models) {
    Permission.hasMany(models.RolePermission, { foreignKey: 'permission_id', as: 'rolePermissions' });
    Permission.belongsToMany(models.Role, { through: models.RolePermission, foreignKey: 'permission_id', as: 'roles' });
  };

  return Permission;
};

