import { Model, model, Schema } from "mongoose";
import { IConversation } from "../interfaces/models/conversationInterface";

const ConversationSchema = new Schema<IConversation>(
  {
    participants: {
      type: [{ type: Schema.Types.ObjectId, ref: "User" }],
      required: true,
      validate: {
        validator(v: unknown[]) {
          return Array.isArray(v) && v.length === 2;
        },
        message: "Conversation must have exactly two participants",
      },
    },
    lastMessageAt: { type: Date, default: null },
    lastMessagePreview: {
      type: String,
      trim: true,
      maxlength: 200,
      default: null,
    },
    unreadCounts: {
      type: Map,
      of: Number,
      default: {},
    },
  },
  { timestamps: true },
);

ConversationSchema.index(
  { "participants.0": 1, "participants.1": 1 },
  { unique: true, name: "participants_pair_unique" },
);
ConversationSchema.index({ participants: 1, lastMessageAt: -1 });

const ConversationModel: Model<IConversation> = model<IConversation>(
  "Conversation",
  ConversationSchema,
);

export default ConversationModel;
