import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';
import { EReserveTypes } from '../enums/reserve-types.enum';

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

export interface IReserveSummaryItem {
  amount: number;
  advanceRate: number;
  availability: number;
}

export interface IReserveSummary {
  [summaryField: string]: IReserveSummaryItem
}

export interface IReserveItem {
  active: boolean;
  reserveName: string;
  type: string;
  amount: number;
}

export interface IReserve {
  bbcDateId: mongoose.Types.ObjectId;
  summary: IReserveSummary;
  items: IReserveItem[];
  notes: string;
}

export interface IReserveDoc extends IReserve, Document {
}

export const ReserveSchema = new mongoose.Schema(
  {
    bbcDateId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.BBCDates,
      required: true,
    },
    summary: {
      [EReserveTypes.RENT]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.PAYROLL]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.INSURANCE]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.TAX]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.OTHER]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.INVENTORY]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.RECEIVABLES]: {
        amount: {
          type: Number,
          required: true,
        }
      },
      [EReserveTypes.EQUIPMENT]: {
        amount: {
          type: Number,
          required: true,
        }
      },
    },
    items: [
      {
        active: {
          type: Boolean,
          required: true,
        },
        reserveName: {
          type: String,
          trim: true,
          required: true,
        },
        type: {
          type: String,
          required: true,
          trim: true,
        },
        amount: {
          type: Number,
          required: true,
        },
      },
    ],
    notes: {
      type: String,
      required: false,
      trim: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true }
);

ReserveSchema.plugin(mongooseLeanId);

export default mongoose.model<IReserveDoc>(MODEL_NAMES.reserves, ReserveSchema);
