const mongoose = require("mongoose");
const AUDIT_ACTIONS = require("../constants/auditAction");

const auditLogSchema = new mongoose.Schema({
  model: {
    type: String,
    required: true,
  },

  documentId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
  },

  action: {
    type: String,
    enum: Object.values(AUDIT_ACTIONS),
    required: true,
  },

  before: {
    type: mongoose.Schema.Types.Mixed,
    default: null,
  },

  after: {
    type: mongoose.Schema.Types.Mixed,
    default: null,
  },

  changes: {
    type: [
      {
        field: String,
        before: mongoose.Schema.Types.Mixed,
        after: mongoose.Schema.Types.Mixed,
      },
    ],
    default: [],
  },

  ipAddress: {
    type: String,
    required: true,
  },

  userAgent: {
    type: String,
    default: "",
  },

  performedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    default: null,
  },

  createdAt: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("AuditLog", auditLogSchema); // Index for faster queries
