import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';

export const LOAN_PAYMENT_FIELDS = [
  '_id',
  'date',
  'productId',
  'amount',
  'paid',
  'settlementCode',
  'paymentOrder',
];

export interface ICombinedPayment {
  borrowerId: string;
  date: Date;
  payment: number;
  addToRevolver: boolean;
  products: {
    productId: string;
    payableSum: number;
    settlementCode: string;
    paymentOrder: string[];
  }[];
  linkedProducts: {
    productId: string;
    payableSum: number;
    settlementCode: string;
  }[];
}

export interface ILoanPayment {
  date: Date;
  productId: mongoose.Types.ObjectId;
  amount: number;
  paid: { _id?: mongoose.Types.ObjectId, statementId: mongoose.Types.ObjectId, amount: number }[];
  loanTransactions: { _id?: mongoose.Types.ObjectId, transactionId: mongoose.Types.ObjectId, amount: number }[];
  settlementCode?: string;
  paymentOrder?: string[];
}

export interface ILoanPaymentWithId extends ILoanPayment {
  _id: mongoose.Types.ObjectId;
}

export interface ILoanPaymentDoc extends ILoanPayment, Document {
}

export const LoanPaymentSchema = new mongoose.Schema(
  {
    date: {
      type: Date,
      required: true,
    },
    productId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanProducts,
      required: true,
    },
    amount: {
      type: Number,
      required: true,
    },
    paid: [
      {
        statementId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: MODEL_NAMES.loanStatements,
        },
        amount: {
          type: Number,
        },
      },
    ],
    loanTransactions: [
      {
        transactionId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: MODEL_NAMES.loanTransactions,
        },
        amount: {
          type: Number,
        },
      },
    ],
    settlementCode: {
      type: String,
      trim: true,
    },
    paymentOrder: [{
      type: String,
    }],
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const LoanPaymentModel: mongoose.Model<ILoanPaymentDoc> = mongoose.model<ILoanPaymentDoc>(MODEL_NAMES.loanPayments, LoanPaymentSchema);
