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

import { MODEL_NAMES } from './_models';

export const LoanBrokerValidationSchema = Joi.object({
  _id: Joi.string().allow(null),
  order: Joi.number(),
  active: Joi.boolean().required(),
  name: Joi.string().required(),
  emails: Joi.array(),
});

export interface ILoanBrokerEmail {
  _id?: mongoose.Types.ObjectId | string
  email: string,
  title: string,
  isActive: boolean
}

export interface ILoanBroker {
  order: number;
  active: boolean;
  name: string;
  emails: ILoanBrokerEmail[];
}

export interface ILoanBrokerWithId extends ILoanBroker {
  _id: mongoose.Types.ObjectId;
}

export type ILoanBrokerView = Omit<ILoanBrokerWithId, 'order'>

export interface ILoanBrokerDoc extends ILoanBroker, Document {
}

export const LoanBrokerSchema = new mongoose.Schema(
  {
    order: {
      type: Number,
      required: true,
    },
    active: {
      type: Boolean,
      required: true,
    },
    name: {
      type: String,
      required: true,
      trim: true,
    },
    emails: [{
      email: {
        type: String,
        required: true,
        trim: true,
      },
      title: {
        type: String,
        required: true,
        trim: true,
      },
      isActive: {
        type: Boolean,
        required: true,
      },
    }],
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const LoanBrokerModel: mongoose.Model<ILoanBrokerDoc> = mongoose.model<ILoanBrokerDoc>(MODEL_NAMES.loanBrokers, LoanBrokerSchema);
