import mongoose, { Model } from 'mongoose';

import {
  IUploadedBankTransactionWithInfo,
} from './UploadedBankTransaction.model';
import { AccountSchema } from './CashAllocationProduct.model';
import { MODEL_NAMES } from './_models';

export interface IAllocatedBankTransaction {
  _id?: mongoose.Types.ObjectId;
  order: number;
  uploadedBankTransactionId: mongoose.Types.ObjectId;
  date: Date;
  accountNumber: string;
  amount: number;
  reference: string;
  cashAllocationProductId: mongoose.Types.ObjectId;
  accounts: {
    [companyId: string]: {
      accountId1: mongoose.Types.ObjectId | 'BANK';
      accountId2: mongoose.Types.ObjectId | 'BANK';
    };
  };
  class: string;
  location: string;
  cashAllocationReferenceId: mongoose.Types.ObjectId;
  splitTransactionId: mongoose.Types.ObjectId;
  memo: string;
}

type AllocatedBankTransactionModel = Model<IAllocatedBankTransaction>;

export type PreSplitUploadedBankTransactionWithInfo = IUploadedBankTransactionWithInfo & { splitTransactionId: mongoose.Types.ObjectId, splitMemo: string };

export const AllocatedBankTransactionSchema = new mongoose.Schema<IAllocatedBankTransaction, AllocatedBankTransactionModel>({
  uploadedBankTransactionId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: MODEL_NAMES.uploadedBankTransactions,
    required: false,
  },
  order: {
    type: Number,
    required: true,
  },
  date: {
    type: Date,
    required: true,
  },
  accountNumber: {
    type: String,
    required: false,
    trim: true,
  },
  amount: {
    type: Number,
    required: true,
  },
  reference: {
    type: String,
    required: false,
    trim: true,
  },
  class: {
    type: String,
    required: false,
    trim: true,
  },
  location: {
    type: String,
    required: false,
    trim: true,
  },
  cashAllocationReferenceId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: MODEL_NAMES.cashAllocationReferences,
    required: false,
  },
  cashAllocationProductId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: MODEL_NAMES.cashAllocationProducts,
    required: false,
  },
  splitTransactionId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: MODEL_NAMES.cashAllocationReferences,
    required: false,
  },
  memo: {
    type: String,
    required: false,
    trim: true,
  },
  accounts: AccountSchema,
}, { timestamps: { createdAt: true, updatedAt: false } });

export const AllocatedBankTransaction = mongoose.model<IAllocatedBankTransaction, AllocatedBankTransactionModel>(MODEL_NAMES.allocatedBankTransactions, AllocatedBankTransactionSchema);
