import mongoose from 'mongoose';

import { MODEL_NAMES } from './_models';
import { ITermLoanSettingsOnly } from './TermLoanSettings.model';

export enum ETermLoanStatus {
  NEW = 'NEW',
  CALCULATED = 'CALCULATED',
  CALCULATING = 'CALCULATING',
  ERROR = 'ERROR',
  EXPECTED = 'EXPECTED',
}

export const TERM_LOAN_FIELDS = [
  '_id',
  'productId',
  'loanStartDate',
  'initialBalance',
  'interestRate',
  'adminRate',
  'primeRate',
  'actual',
  'isMismatched',
  'lastCalculated',
  'calculationStatus',
];

export interface ITermLoan {
  productId: mongoose.Types.ObjectId;
  loanStartDate: Date;
  initialBalance: number;
  interestRate: number;
  adminRate: number;
  primeRate: number;
  actual: boolean;
  isMismatched: boolean;
  lastCalculated: Date;
  calculationStatus: ETermLoanStatus;
}

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

export interface ITermLoanLean extends ITermLoan {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface ITermLoanPlain extends Omit<ITermLoan, 'productId'> {
  _id: string;
  productId: string;
}

export interface ITermLoanView extends ITermLoan {
  _id: mongoose.Types.ObjectId;
  settings: ITermLoanSettingsOnly;
}

export interface ITermLoanDoc extends ITermLoan, mongoose.Document {
}

export type TTermLoanModel = mongoose.Model<ITermLoan>;

export const TermLoanSchema = new mongoose.Schema(
  {
    productId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanProducts,
      required: true,
    },
    loanStartDate: {
      type: Date,
      required: true,
    },
    initialBalance: {
      type: Number,
      required: true,
    },
    interestRate: {
      type: Number,
      required: true,
    },
    adminRate: {
      type: Number,
      required: true,
    },
    primeRate: {
      type: Number,
      required: true,
    },
    actual: {
      type: Boolean,
      required: true,
    },
    isMismatched: {
      type: Boolean,
      required: true,
    },
    lastCalculated: {
      type: Date,
      required: true,
    },
    calculationStatus: {
      type: String,
      required: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const TermLoanModel: mongoose.Model<ITermLoanDoc> = mongoose.model<ITermLoanDoc>(MODEL_NAMES.termLoan, TermLoanSchema);
