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

import { MODEL_NAMES } from './_models';
import { ILoanStatementStatus } from './LoanStatementStatus.model';

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

export interface ICreateBBCDate {
  date: Date;
  inventory: boolean;
  receivables: boolean;
  borrowerId: string;
}

export const ICreateBBCDateSchema = Joi.object({
  date: Joi.date().required(),
  inventory: Joi.boolean().required(),
  receivables: Joi.boolean().required(),
  borrowerId: Joi.string().required(),
});

export interface IBBCDate {
  borrowerId: mongoose.Types.ObjectId;
  bbcDate: Date;
}

export interface IBBCDateDoc extends IBBCDate, mongoose.Document {
}

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

export type TBBCDateDoc = mongoose.HydratedDocument<ILoanStatementStatus>;

export interface IBBCDateLean extends IBBCDate {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBBCDatePlain extends Omit<IBBCDate, 'borrowerId'> {
  _id: string;
  borrowerId: string;
}

export type TBBCDateModel = mongoose.Model<IBBCDate>;

export const BBCDateSchema = new mongoose.Schema(
  {
    borrowerId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.borrowers,
      required: true,
    },
    bbcDate: {
      type: Date,
      required: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

BBCDateSchema.plugin(mongooseLeanId);

BBCDateSchema.index({
  borrowerId: 1,
  bbcDate: -1,
});

export const BBCDateModel: mongoose.Model<IBBCDateDoc> = mongoose.model<IBBCDateDoc>(MODEL_NAMES.BBCDates, BBCDateSchema);
