import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';
import { IComplianceBorrower } from './BorrowerCompliance.model';

const mongooseLeanId = require('../plugins/id.plugin');

export enum EComplianceItemStatus {
  NEW = 'NEW',
  ACCEPTED = 'ACCEPTED',
  REJECTED = 'REJECTED',
  IN_REVIEW = 'IN_REVIEW',
}

export interface IEmailRecipient {
  email: string;
  title?: string;
  isActive: boolean;
}

export interface IEmailRecipientLean extends IEmailRecipient {
  _id?: mongoose.Types.ObjectId;
}

export interface IEmailRecipientDocument extends IEmailRecipient, Document {
}

export interface IComplianceItem {
  name: string;
  importanceScore: number;
  notificationDays: number;
  multiplier: number;
}

export interface IBorrowerItem {
  item: IComplianceItemDocument;
  startDate: Date;
  frequency: string;
  instances: IBorrowerItemInstanceDocument[];
  emailAddresses: IEmailRecipientDocument[];
}

export interface IComplianceFile {
  _id?: string;
  fileId: string;
  name: string;
  isFileNew?: boolean;
  uploadedAt?: Date;
  uploadedBy?: string;
}

export interface IBorrowerItemInstance {
  nextDate: Date;
  submittedDate: Date;
  status: EComplianceItemStatus;
  files?: IComplianceFile[];
}

export interface IBorrowerItemInstanceLean extends IBorrowerItemInstance {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBorrowerItemInstanceDocument extends IBorrowerItemInstance, Document {
}

export interface IComplianceItemDocument extends IComplianceItem, Document {
}

export interface IBorrowerItemDocument extends IBorrowerItem, Document {
}

export interface IBorrowerItemLean extends Omit<IBorrowerItem, 'instances' | 'emailAddresses'> {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
  instances: IBorrowerItemInstanceLean[];
  emailAddresses: IEmailRecipientLean[];
}

export const ComplianceItemSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: true,
    },
    importanceScore: {
      type: Number,
      required: true,
    },
    notificationDays: {
      type: Number,
      required: true,
    },
    multiplier: {
      type: Number,
      required: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

ComplianceItemSchema.plugin(mongooseLeanId);

export const ComplianceItemModel: mongoose.Model<IComplianceItemDocument> = mongoose.model<IComplianceItemDocument>(MODEL_NAMES.complianceItems, ComplianceItemSchema);
