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

import { MODEL_NAMES } from './_models';

export interface IAuditorContact {
  auditorId: mongoose.Types.ObjectId;
  isDeleted: boolean;
  name: string;
  email?: string;
  normalizedEmail?: string;
  phone?: string;
  comment?: string;
  order?: number;
}

export type IAuditorContactDoc = HydratedDocument<IAuditorContact>;

export interface IAuditorContactLean extends IAuditorContact {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IAuditorContactPlain extends Omit<IAuditorContact, 'auditorId'> {
  _id: string;
  auditorId: string;
  createdAt: Date;
  updatedAt: Date;
}

export const AuditorContactValidationSchema = Joi.object({
  _id: Joi.string(),
  auditorId: Joi.string(),
  name: Joi.string().required(),
  email: Joi.string().allow(''),
  phone: Joi.string().allow(''),
  comment: Joi.string().allow(''),
  isDeleted: Joi.boolean(),
  order: Joi.number().required().allow(null),
});

export type AuditorContactModel = mongoose.Model<IAuditorContact>;

export const AuditorContactSchema = new mongoose.Schema<IAuditorContact, AuditorContactModel>(
  {
    auditorId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.auditors,
      required: true,
    },
    isDeleted: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
    },
    normalizedEmail: {
      type: String,
      lowercase: true,
      select: false,
      unique: true,
    },
    phone: {
      type: String,
    },
    comment: {
      type: String,
    },
    order: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

export const AuditorContact = mongoose.model<IAuditorContact, AuditorContactModel>(MODEL_NAMES.auditorContact, AuditorContactSchema);
