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

import { MODEL_NAMES } from './_models';

export interface IUnderwriter {
  isDeleted: boolean;
  name: string;
  email: string;
  order?: number;
  userId?: string;
}

export interface IUnderwriterDoc extends IUnderwriter, Document {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IUnderwriterLean extends IUnderwriter {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IUnderwriterPlain extends IUnderwriter {
  _id: string;
  createdAt: Date;
  updatedAt: Date;
}

export type UnderwriterModel = Model<IUnderwriterDoc>;

export const UnderwriterValidationSchema = Joi.object({
  _id: Joi.string(),
  name: Joi.string().required(),
  email: Joi.string(),
  userId: Joi.string(),
  isDeleted: Joi.boolean(),
  order: Joi.number().required().allow(null),
});

export const UnderwriterSchema = new mongoose.Schema<IUnderwriter, UnderwriterModel>(
  {
    isDeleted: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
      required: true,
    },
    order: {
      type: Number,
      required: true,
    },
    email: {
      type: String,
    },
    userId: {
      type: String,
      required: false,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

export const Underwriter = mongoose.model<IUnderwriter, UnderwriterModel>(MODEL_NAMES.underwriters, UnderwriterSchema);
