import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';
import { ICollateralItem } from '../interfaces/collaterals.interface';
import { IBBCSheetDoc } from './BBCSheet.model';
import { IBBCDateDoc } from './BBCDate.model';

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

export const RECEIVABLE_FIELDS = [
  '_id',
  'invoiceDate',
  'invoiceNumber',
  'customerTitle',
  'dueDate',
  'invoiceAmount',
  'originalAmount',
  'invoiceDetail1',
  'invoiceDetail2',
  'invoiceDetail3',
];

export interface IReceivableItem extends ICollateralItem {
  invoiceDate: Date;
  invoiceNumber: string;
  customerTitle: string;
  dueDate: number;
  invoiceAmount: number;
  originalAmount: number;
  invoiceDetail1: string;
  invoiceDetail2: string;
  invoiceDetail3: string;
}

export interface IReceivableItemDoc extends IReceivableItem, Document {
}

export interface IReceivableItemDocPopulated extends IReceivableItemDoc {
  bbc: IBBCDateDoc;
  bbcSheet: IBBCSheetDoc;
}

export const ReceivableItemSchema = new mongoose.Schema(
  {
    bbcSheetId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.BBCSheets,
      required: true,
    },
    order: {
      type: Number,
      required: true,
    },
    invoiceNumber: {
      type: String,
      trim: true,
      required: true,
    },
    invoiceDate: {
      type: Date,
      required: true,
    },
    customerTitle: {
      type: String,
      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 }
);

ReceivableItemSchema.index({ customerTitle: 'text' });

ReceivableItemSchema.plugin(mongooseLeanId);

export const ReceivableItemModel: mongoose.Model<IReceivableItemDoc> = mongoose.model<IReceivableItemDoc>(MODEL_NAMES.receivableItems, ReceivableItemSchema);
