import mongoose from 'mongoose';
import Joi from 'joi';

import { MODEL_NAMES } from './_models';

export interface IHistoricalLoanCharge {
  loanProductId: mongoose.Types.ObjectId;
  date: Date;
  paymentDate: Date;
  source: string;
  chargeId: mongoose.Types.ObjectId;
  chargeName: string;
  amount: number;
  amountPaid: number;
}

export type THistoricalLoanChargeDoc = mongoose.HydratedDocument<IHistoricalLoanCharge>;

export interface IHistoricalLoanChargeLean extends IHistoricalLoanCharge {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IHistoricalLoanChargePlain extends Omit<IHistoricalLoanCharge, 'loanProductId' | 'chargeId'> {
  _id: string;
  loanProductId: string;
  chargeId: string;
  createdAt: Date;
  updatedAt: Date;
}

export const HistoricalLoanChargeCreateValidationSchema = Joi.object({
  loanProductId: Joi.string().required(),
  date: Joi.date().required(),
  paymentDate: Joi.date().required(),
  chargeId: Joi.string().required(),
  source: Joi.string().required(),
  chargeName: Joi.string().required(),
  amount: Joi.number().required(),
  amountPaid: Joi.number().required(),
});

export const HistoricalLoanChargeUpdateValidationSchema = Joi.object({
  _id: Joi.string().required(),
  loanProductId: Joi.string(),
  date: Joi.date(),
  paymentDate: Joi.date(),
  chargeId: Joi.string(),
  source: Joi.string(),
  chargeName: Joi.string(),
  amount: Joi.number(),
  amountPaid: Joi.number(),
});

export type THistoricalLoanChargeModel = mongoose.Model<IHistoricalLoanCharge>;

export const HistoricalLoanChargeSchema = new mongoose.Schema<IHistoricalLoanCharge, THistoricalLoanChargeModel>(
  {
    loanProductId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanProducts,
      required: true,
    },
    date: {
      type: Date,
      required: true,
    },
    paymentDate: {
      type: Date,
      required: true,
    },
    source: {
      type: String,
      required: true,
    },
    chargeId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanCharges,
      required: true,
    },
    chargeName: {
      type: String,
      required: true,
    },
    amount: {
      type: Number,
      required: true,
    },
    amountPaid: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

HistoricalLoanChargeSchema.index(
  { loanProductId: 1, chargeId: 1, date: 1 },
  { unique: true },
);

export const HistoricalLoanCharge = mongoose.model<IHistoricalLoanCharge, THistoricalLoanChargeModel>(MODEL_NAMES.historicalLoanCharges, HistoricalLoanChargeSchema);
