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

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

export const schemaModel = {
  investor: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    required: true,
    index: true,
  },
  fundSeoRegisterNo: {
    type: String,
    required: true,
    index: true,
  },
  fundName: String,
  trackId: {
    type: String,
    required: true,
    unique: true,
    index: true,
  },
  transaction: {
    type: mongooseSchema.Types.ObjectId,
    ref: "Transaction",
    default: undefined,
  },
  operationType: {
    type: String,
    enum: ["issuance", "redemption"],
    default: "issuance",
    index: true,
  },
  paymentMethod: {
    type: String,
    enum: ["gateway", "card", "slip"],
    default: "gateway",
    index: true,
  },
  paymentCard: {
    type: mongooseSchema.Types.ObjectId,
    ref: "PaymentCard",
    index: true,
  },
  paymentSlip: {
    type: mongooseSchema.Types.ObjectId,
    ref: "PaymentSlip",
    index: true,
  },
  meta: {
    type: mongooseSchema.Types.Mixed,
    default: undefined,
  },
  paymentGateway: mongooseSchema.Types.Mixed,
  amountRial: {
    type: Number,
    default: 0,
  },
  units: {
    type: Number,
    default: 0,
  },
  unitPrice: {
    type: Number,
    default: 0,
  },
  status: {
    type: String,
    enum: ["wait_for_payment", "reviewing", "approved", "rejected", "failed"],
    default: "wait_for_payment",
    index: true,
  },
  externalSource: {
    type: String,
    trim: true,
    default: "",
    index: true,
  },
  externalId: {
    type: String,
    trim: true,
    default: "",
    index: true,
  },
  externalStatus: {
    type: String,
    trim: true,
    default: "",
  },
  externalLastResponse: {
    type: mongooseSchema.Types.Mixed,
    default: undefined,
  },
  externalLastSyncedAt: {
    type: Date,
    default: null,
    index: true,
  },
};

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

schema.index({ investor: 1, status: 1 });
schema.index({ createdAt: -1 });
schema.index({ investor: 1, createdAt: -1 });
schema.index({ status: 1, createdAt: -1 });
schema.index({ externalSource: 1, status: 1, externalLastSyncedAt: 1 });
schema.index(
  { transaction: 1 },
  {
    unique: true,
    partialFilterExpression: {
      transaction: { $type: "objectId" },
    },
  },
);

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