// Connections
import mongoConnection from "$connections/mongo/mongo.connection.js";

import mongoose from "mongoose";
const mongooseSchema = mongoose.Schema;

export const schemaModel = {
  request: {
    type: mongooseSchema.Types.ObjectId,
    ref: "Request",
    required: true,
    index: true,
  },
  actorType: {
    type: String,
    enum: ["user", "system"],
    default: "system",
    index: true,
  },
  actorUser: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    default: null,
    index: true,
  },
  source: {
    type: String,
    trim: true,
    default: "",
    index: true,
  },
  eventType: {
    type: String,
    trim: true,
    required: true,
    index: true,
  },
  changedFields: {
    type: mongooseSchema.Types.Mixed,
    default: {},
  },
  snapshot: {
    type: mongooseSchema.Types.Mixed,
    default: {},
  },
  notes: {
    type: String,
    trim: true,
    default: "",
  },
};

export const schema = new mongooseSchema(schemaModel, {
  timestamps: { createdAt: true, updatedAt: false },
});

schema.index({ request: 1, createdAt: 1 });
schema.index({ request: 1, eventType: 1, createdAt: 1 });

export default mongoConnection.model("RequestHistory", schema);
