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

import { MODEL_NAMES } from './_models';

export interface IAppraiserContact {
  appraiserId: mongoose.Types.ObjectId;
  isDeleted: boolean;
  name?: string;
  title?: string;
  emails?: string[];
  normalizedEmails?: string[];
  phone?: string;
  comment?: string;
  order?: number;
}

export interface IAppraiserContactWithID extends IAppraiserContact {
  _id: string;
}

export interface IAppraiserContactDoc extends IAppraiserContact, Document {
}

export const AppraiserContactValidationSchema = Joi.object({
  _id: Joi.string(),
  appraiserId: Joi.string(),
  name: Joi.string().allow(''),
  title: Joi.string().allow(''),
  emails: Joi.array().items(Joi.string().email()).allow(null),
  phone: Joi.string().allow(''),
  comment: Joi.string().allow(''),
  isDeleted: Joi.boolean(),
  order: Joi.number().required().allow(null),
});

export type AppraiserContactModel = Model<IAppraiserContact, object, object>;

export const AppraiserContactSchema = new mongoose.Schema<IAppraiserContact, AppraiserContactModel>(
  {
    appraiserId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.appraiser,
      required: true,
    },
    isDeleted: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
    },
    title: {
      type: String,
    },
    emails: {
      type: [String],
    },
    normalizedEmails: {
      type: [String],
      lowercase: true,
      select: false,
      // unique: true, // TODO potential issue with unique email normalization
    },
    phone: {
      type: String,
    },
    comment: {
      type: String,
    },
    order: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

export const AppraiserContact = mongoose.model<IAppraiserContact, AppraiserContactModel>(MODEL_NAMES.appraiserContact, AppraiserContactSchema);
