import mongoose, { Document } from 'mongoose';

import { MODEL_NAMES } from './_models';
import { IBBCDate } from './BBCDate.model';
import { InventoryItemModel } from './InventoryItem.model';
import { AccountPayableItemModel } from './AccountPayableItem.model';
import { ReceivableItemModel } from './ReceivableItem.model';
import { SalesItem } from './SalesItem.model';

export interface IBBCSheet {
  bbcDateId: mongoose.Types.ObjectId;
  dataType: string;
  uploadUser: string;
  fileHash: string;
  fileName: string;
  sheetName: string;
  comment: string;
}

export interface IBBCSheetDoc extends IBBCSheet, Document {
}

export type TIBBCSheet = mongoose.HydratedDocument<IBBCSheet>;

export interface IBBCSheetLean extends IBBCSheet {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBBCSheetPlain extends Omit<IBBCSheet, 'bbcDateId'> {
  _id: string;
  bbcDateId: string;
}

export type TBBCSheetModel = mongoose.Model<IBBCSheet>;

export interface IBBCSheetWithBBCDate extends IBBCSheetDoc {
  bbcDate: IBBCDate;
}

export const BBCSheetSchema = new mongoose.Schema(
  {
    bbcDateId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.BBCDates,
      required: true,
    },
    dataType: {
      type: String,
      required: true,
      trim: true,
    },
    uploadUser: {
      type: String,
    },
    fileHash: {
      type: String,
      trim: true,
    },
    fileName: {
      type: String,
      trim: true,
    },
    sheetName: {
      type: String,
      trim: true,
    },
    comment: {
      type: String,
      trim: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true }
);

BBCSheetSchema.pre('findOneAndDelete', async function () {
  const bbcSheetId = this.getQuery()['_id'];
  await InventoryItemModel.deleteMany({ bbcSheetId: bbcSheetId });
  await ReceivableItemModel.deleteMany({ bbcSheetId: bbcSheetId });
  await AccountPayableItemModel.deleteMany({ bbcSheetId: bbcSheetId });
  await SalesItem.deleteMany({ bbcSheetId: bbcSheetId });
});

BBCSheetSchema.index({
  dataType: 1,
  bbcDateId: 1,
});

export const BBCSheetModel: mongoose.Model<IBBCSheetDoc> = mongoose.model<IBBCSheetDoc>(MODEL_NAMES.BBCSheets, BBCSheetSchema);
