import mongoose, { Model, Document } from 'mongoose';
import Joi from 'joi';

import { MODEL_NAMES } from './_models';

export interface ICRMProspectLink {
  prospectId: mongoose.Types.ObjectId;
  auditorLinks: Map<string, mongoose.Types.ObjectId>;
  clientLinkId: string;
}

export interface ICRMProspectLinkDoc extends Document {
  prospectId: mongoose.Types.ObjectId;
  auditorLinks: Map<string, mongoose.Types.ObjectId>;
  clientLinkId: string;
}

export interface ICRMProspectLinkWithId extends ICRMProspectLink {
  _id: string;
}

export interface ICRMProspectLinkWithPureLinks extends ICRMProspectLinkWithId {
  pureLinks: {
    auditorLinks: { [auditorTitle: string]: string };
    clientLink: string;
  };
}

export const ICRMProspectLinkValidationSchema = Joi.object({
  _id: Joi.string(),
  prospectId: Joi.string().required(),
  auditorLinkId: Joi.string().required(),
  clientLinkId: Joi.string().required(),
});

export type CRMProspectLinkModel = Model<ICRMProspectLink, object, object>;

export const ProspectLinkSchema = new mongoose.Schema<ICRMProspectLink, CRMProspectLinkModel>(
  {
    prospectId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.CRMProspects,
      required: true,
    },
    auditorLinks: {
      type: Map,
      of: mongoose.Schema.Types.ObjectId,
      required: true,
    },
    clientLinkId: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

export const CRMProspectLink = mongoose.model<ICRMProspectLink, CRMProspectLinkModel>(MODEL_NAMES.prospectLinks, ProspectLinkSchema);
