import { DataTypes } from 'sequelize';
import sequelize from '../config/database.js';

/**
 * ConfigAuditLog Model
 * Immutable record of every configuration change.
 */
const ConfigAuditLog = sequelize.define('ConfigAuditLog', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  configId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'config_id',
    references: {
      model: 'config_settings',
      key: 'id'
    }
  },
  actorId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'actor_id',
    comment: 'User ID who made the change',
    references: {
      model: 'users',
      key: 'id'
    }
  },
  action: {
    type: DataTypes.ENUM('CREATE', 'UPDATE', 'DELETE'),
    allowNull: false
  },
  previousValue: {
    type: DataTypes.JSONB,
    allowNull: true,
    field: 'previous_value',
    comment: 'Snapshot of value before change (encrypted if secret)'
  },
  newValue: {
    type: DataTypes.JSONB,
    allowNull: true,
    field: 'new_value',
    comment: 'Snapshot of value after change (encrypted if secret)'
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    field: 'created_at'
  }
}, {
  tableName: 'config_audit_logs',
  timestamps: false, // Only creation time matters for audit logs
  indexes: [
    {
      fields: ['configId']
    },
    {
      fields: ['actorId']
    },
    {
      fields: ['createdAt']
    }
  ]
});

export default ConfigAuditLog;
