module.exports = (sequelize, DataTypes) => {
  const PermissionAudit = sequelize.define('PermissionAudit', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'User',
        key: 'id'
      },
      comment: 'User who performed the action'
    },
    permission_code: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'Permission code that was checked'
    },
    action: {
      type: DataTypes.ENUM('GRANTED', 'REVOKED', 'DENIED'),
      allowNull: false,
      comment: 'Action performed: GRANTED (access allowed), REVOKED (permission removed), DENIED (access denied)'
    },
    resource_type: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: 'Type of resource accessed (e.g., purchase_order, material)'
    },
    resource_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'ID of the resource accessed'
    },
    ip_address: {
      type: DataTypes.STRING(45),
      allowNull: true,
      comment: 'IP address of the user'
    },
    user_agent: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'User agent string'
    }
  }, {
    tableName: 'permission_audit',
    timestamps: true,
    underscored: true,
    createdAt: 'created_at',
    updatedAt: false,         // DB table has no updated_at column
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['permission_code']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['resource_type', 'resource_id']
      }
    ]
  });

  PermissionAudit.associate = function (models) {
    PermissionAudit.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user'
    });
  };

  return PermissionAudit;
};

