import mongoose, { Model } from 'mongoose';

import { MODEL_NAMES } from './_models';

export interface IBorrowerReminders {
  borrowerId: mongoose.Types.ObjectId;
  appraisal: {
    reportDate?: Date;
    asOfDate?: Date;
    firm?: string;
    nextDue?: Date;
    nextScheduled?: boolean;
  };
  fieldExam: {
    reportDate?: Date;
    asOfDate?: Date;
    firm?: string;
    nextDue?: Date;
    nextScheduled?: boolean;
  };
  insurance: {
    expirationDate?: Date;
    company?: string;
    comments?: string;
  };
}

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

export interface IBorrowerRemindersLean extends IBorrowerReminders {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBorrowerRemindersPlain extends Omit<IBorrowerReminders, 'borrowerId'> {
  _id: string;
  borrowerId: string;
}

export type TBorrowerRemindersModel = Model<IBorrowerReminders>;

const ReminderSectionSchema = new mongoose.Schema(
  {
    reportDate: { type: Date },
    asOfDate: { type: Date },
    firm: { type: String },
    nextDue: { type: Date },
    nextScheduled: { type: Boolean },
  },
  { _id: false }
);

const InsuranceReminderSchema = new mongoose.Schema(
  {
    expirationDate: { type: Date },
    company: { type: String },
    comments: { type: String },
  },
  { _id: false }
);

export const BorrowerRemindersSchema = new mongoose.Schema<IBorrowerReminders, TBorrowerRemindersModel>(
  {
    borrowerId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.borrowers,
      required: true,
    },
    appraisal: {
      type: ReminderSectionSchema,
      default: {},
    },

    fieldExam: {
      type: ReminderSectionSchema,
      default: {},
    },

    insurance: {
      type: InsuranceReminderSchema,
      default: {},
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
    minimize: false,
  },
);

export const BorrowerReminders = mongoose.model<IBorrowerReminders, TBorrowerRemindersModel>(MODEL_NAMES.borrowerReminders, BorrowerRemindersSchema);

BorrowerRemindersSchema.set('toJSON', {
  versionKey: false,
  transform: (_doc, ret: any) => {
    delete ret._id;
    delete ret.__v;
    delete ret.createdAt;
    delete ret.updatedAt;
    return ret;
  },
});

BorrowerRemindersSchema.set('toObject', {
  versionKey: false,
  transform: (_doc, ret: any) => {
    delete ret._id;
    delete ret.__v;
    delete ret.createdAt;
    delete ret.updatedAt;
    return ret;
  },
});

BorrowerRemindersSchema.index(
  { borrowerId: 1 },
  { unique: true },
);
