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,
  },
  reward: {
    type: mongooseSchema.Types.ObjectId,
    ref: "ClubReward",
    required: true,
    index: true,
  },
  pointsSpent: {
    type: Number,
    required: true,
    min: 1,
  },
  status: {
    type: String,
    enum: ["pending", "fulfilled", "failed"],
    default: "pending",
    index: true,
  },
  paymentCard: {
    type: mongooseSchema.Types.ObjectId,
    ref: "PaymentCard",
    default: null,
    index: true,
  },
  paymentBatch: {
    type: mongooseSchema.Types.ObjectId,
    ref: "PaymentBatchCard",
    default: null,
    index: true,
  },
  spendTransaction: {
    type: mongooseSchema.Types.ObjectId,
    ref: "ClubPointTransaction",
    default: null,
  },
  reversalTransaction: {
    type: mongooseSchema.Types.ObjectId,
    ref: "ClubPointTransaction",
    default: null,
  },
  fulfilledAt: {
    type: Date,
    default: null,
  },
  meta: {
    type: mongooseSchema.Types.Mixed,
    default: {},
  },
};

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

schema.index({ user: 1, createdAt: -1 });
schema.index({ status: 1, createdAt: -1 });

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