import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';

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

interface IInventoryItemInner {
  bbcDate: Date;
  sku: string;
  category: string;
  lotNumber: number;
  location: string;
  skuDescription1: string;
  skuDescription2: string;
  skuDescription3: string;
  skuDate: Date;
  expiryDate: Date;
  qty: number;
  unitCost: number;
  value: number;
}

export interface InventoryDocument extends Document {
  borrowerId: string;
  bbcDate: Date;
  uploadUser: string;
  fileHash: string;
  fileName: string;
  sheetName: string;
  comment: string;
  items: IInventoryItemInner[];
}

export const InventorySchema = new mongoose.Schema(
  {
    borrowerId: {
      type: String,
      trim: true,
      required: true,
    },
    bbcDate: {
      type: Date,
      required: true,
    },
    uploadUser: {
      type: String,
      trim: true,
    },
    fileHash: {
      type: String,
      trim: true,
    },
    fileName: {
      type: String,
      trim: true,
    },
    sheetName: {
      type: String,
      trim: true,
    },
    comment: {
      type: String,
      trim: true,
    },
    items: [
      {
        bbcDate: {
          type: Date,
          required: true,
        },
        skuDate: {
          type: Date,
          required: true,
        },
        category: {
          type: String,
          trim: true,
          required: true,
          default: 'NO CATEGORY',
        },
        sku: {
          type: String,
          trim: true,
          required: true,
        },
        lotNumber: {
          type: String,
          trim: true,
          required: false,
        },
        qty: {
          type: Number,
          required: true,
        },
        value: {
          type: Number,
          required: true,
        },
        expiryDate: {
          type: Date,
        },
        location: {
          type: String,
          trim: true,
        },
        unitCost: {
          type: Number,
        },
        skuDescription1: {
          type: String,
          trim: true,
        },
        skuDescription2: {
          type: String,
          trim: true,
        },
        skuDescription3: {
          type: String,
          trim: true,
        },
      },
    ],
    __v: { type: Number, select: false },
  },
  { timestamps: true }
);

InventorySchema.plugin(mongooseLeanId);

export const InventoryModel: mongoose.Model<InventoryDocument> = mongoose.model<InventoryDocument>(MODEL_NAMES.inventories, InventorySchema);
