import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';

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

export interface IReceivablesItem {
  bbcDate: Date;
  invoiceDate: Date;
  invoiceNumber: string;
  customerTitle: string;
  dueDate: number;
  invoiceAmount: number;
  originalAmount: number;
  invoiceDetail1: string;
  invoiceDetail2: string;
  invoiceDetail3: string;
}

export interface IReceivable {
  borrowerId: string;
  bbcDate: Date;
  uploadUser: string;
  fileHash: string;
  fileName: string;
  sheetName: string;
  invoices: IReceivablesItem[];
}

export interface IReceivableDocument extends IReceivable, Document {
}

export const ReceivableSchema = 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,
    },
    invoices: [
      {
        bbcDate: {
          type: Date,
          required: true,
        },
        invoiceNumber: {
          type: String,
          trim: true,
          required: true,
        },
        invoiceDate: {
          type: Date,
          required: true,
        },
        customerTitle: {
          type: String,
          required: true,
          trim: true,
          default: 'No Title',
        },
        invoiceAmount: {
          type: Number,
          required: true,
        },
        originalAmount: {
          type: Number,
          required: false,
        },
        dueDate: {
          type: Date,
        },
        invoiceDetail1: {
          type: String,
          trim: true,
        },
        invoiceDetail2: {
          type: String,
          trim: true,
        },
        invoiceDetail3: {
          type: String,
          trim: true,
        },
      },
    ],
    __v: { type: Number, select: false },
  },
  { timestamps: true }
);

ReceivableSchema.plugin(mongooseLeanId);

export const ReceivableModel: mongoose.Model<IReceivableDocument> = mongoose.model<IReceivableDocument>(MODEL_NAMES.receivables, ReceivableSchema);
