import mongoose, { Document, Model } from 'mongoose';

import { MODEL_NAMES } from './_models';
import { ECollaterals } from '../enums/collaterals.enum';

export interface ICollateralAdjustmentSummaryItem {
  amount: number;
}

export interface ICollateralAdjustmentSummary {
  [summaryField: string]: ICollateralAdjustmentSummaryItem;
}

export interface ICollateralAdjustmentItem {
  active: boolean;
  name: string;
  type: allowedCollateralTypes;
  amount: number;
}

export interface ICollateralAdjustment {
  bbcDateId: mongoose.Types.ObjectId;
  summary: ICollateralAdjustmentSummary;
  items: ICollateralAdjustmentItem[];
  notes: string;
}

export interface ICollateralAdjustmentDoc extends ICollateralAdjustment, Document {
}

type allowedCollateralTypes = ECollaterals.RECEIVABLE | ECollaterals.INVENTORY | ECollaterals.OTHER;

type AllowedCollateralSubset = {
  [key in ECollaterals]: boolean;
};

const allowedCollateralSubset: Partial<AllowedCollateralSubset> = {
  [ECollaterals.RECEIVABLE]: true,
  [ECollaterals.INVENTORY]: true,
  [ECollaterals.OTHER]: true,
};

export const allowedCollateralTypeValues: Array<keyof typeof ECollaterals> = Object.keys(allowedCollateralSubset).filter((key) => allowedCollateralSubset[key as ECollaterals]) as Array<keyof typeof ECollaterals>;

type CollateralAdjustmentModel = Model<ICollateralAdjustment, {}, {}>;

let collateralAdjustmentSummary = {};

allowedCollateralTypeValues.forEach(collateralType => {
  collateralAdjustmentSummary[collateralType] = {
    amount: {
      type: Number,
      required: true,
    },
  };
});

export const CollateralAdjustmentSchema = new mongoose.Schema<ICollateralAdjustment, CollateralAdjustmentModel>(
  {
    bbcDateId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.BBCDates,
      required: true,
    },
    summary: collateralAdjustmentSummary,
    items: [
      {
        active: {
          type: Boolean,
          required: true,
        },
        name: {
          type: String,
          trim: true,
          required: true,
        },
        type: {
          type: String,
          enum: allowedCollateralTypeValues,
          required: true,
          trim: true,
        },
        amount: {
          type: Number,
          required: true,
        },
      },
    ],
    notes: {
      type: String,
      required: false,
      trim: true,
    },
  },
  { timestamps: true },
);

export const CollateralAdjustment = mongoose.model<ICollateralAdjustment, CollateralAdjustmentModel>(MODEL_NAMES.collateralAdjustments, CollateralAdjustmentSchema);
