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

import mongoose from "mongoose";

const mongooseSchema = mongoose.Schema;

export const schemaModel = {
  user: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    required: true,
    index: true,
  },
  type: {
    type: String,
    enum: ["earned", "spent", "expired", "reversed", "adjusted"],
    required: true,
    index: true,
  },
  points: {
    type: Number,
    required: true,
  },
  originalPoints: {
    type: Number,
    default: 0,
  },
  remainingPoints: {
    type: Number,
    default: 0,
    index: true,
  },
  source: {
    type: String,
    required: true,
    trim: true,
    index: true,
  },
  sourceId: {
    type: mongooseSchema.Types.Mixed,
    default: null,
    index: true,
  },
  eventKey: {
    type: String,
    trim: true,
    default: "",
  },
  meta: {
    type: mongooseSchema.Types.Mixed,
    default: {},
  },
  expiresAt: {
    type: Date,
    default: null,
    index: true,
  },
};

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

schema.index(
  { eventKey: 1 },
  {
    unique: true,
    partialFilterExpression: {
      eventKey: { $type: "string", $ne: "" },
    },
  },
);
schema.index({ user: 1, createdAt: -1 });
schema.index({ user: 1, remainingPoints: 1, expiresAt: 1, createdAt: 1 });

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