import { Model, model, Schema } from "mongoose";
import { IConnection } from "../interfaces/models/connectionInterface";

const ConnectionSchema = new Schema<IConnection>(
  {
    senderId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true,
    },
    receiverId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      default: null,
      index: true,
    },
    inviteeEmail: {
      type: String,
      trim: true,
      lowercase: true,
      default: null,
      index: true,
    },
    status: {
      type: String,
      enum: ["pending", "accepted", "rejected", "cancelled"],
      default: "pending",
      required: true,
      index: true,
    },
  },
  { timestamps: true }
);

ConnectionSchema.pre("validate", function (next) {
  const hasReceiver = this.receiverId != null;
  const hasEmail =
    typeof this.inviteeEmail === "string" && this.inviteeEmail.length > 0;

  if (hasReceiver === hasEmail) {
    next(
      new Error(
        "Connection must have exactly one of receiverId or inviteeEmail",
      ),
    );
    return;
  }
  next();
});

ConnectionSchema.index(
  { senderId: 1, receiverId: 1 },
  {
    unique: true,
    partialFilterExpression: {
      status: "pending",
      receiverId: { $type: "objectId" },
    },
    name: "unique_pending_user_pair",
  }
);

ConnectionSchema.index(
  { senderId: 1, inviteeEmail: 1 },
  {
    unique: true,
    partialFilterExpression: {
      status: "pending",
      inviteeEmail: { $type: "string" },
    },
    name: "unique_pending_email_invite",
  }
);

const ConnectionModel: Model<IConnection> = model<IConnection>(
  "connections",
  ConnectionSchema
);

export default ConnectionModel;
