import mongoose, { Document, Model } from 'mongoose';

import { MODEL_NAMES } from './_models';

export interface IBank {
  isDeleted?: boolean;
  active: boolean;
  order: number;
  bankAccountNumber: string;
  name: string;
  ledgerAccountCodes: {
    [companyId: string]: mongoose.Types.ObjectId;
  };
  reportSettings?: {
    consolidatedAllAccounts?: boolean;
  };
}

export interface IBankWithId extends IBank {
  _id: mongoose.Types.ObjectId;
}

export interface IBankDoc extends IBank, Document {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBankLean extends IBank {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBankPlain extends Omit<IBank, 'ledgerAccountCodes'> {
  _id: string;
  createdAt: Date;
  updatedAt: Date;
  ledgerAccountCodes: {
    [companyId: string]: string;
  };
}

export type IBankView = Omit<IBankWithId, 'order'>

export type IBankModel = Model<IBank>;

export const BankSchema = new mongoose.Schema<IBank, IBankModel>(
  {
    isDeleted: {
      type: Boolean,
      default: false,
    },
    active: {
      type: Boolean,
      required: true,
      default: true,
    },
    order: {
      type: Number,
      required: true,
      default: 0,
    },
    bankAccountNumber: {
      type: String,
      trim: true,
      required: true,
    },
    name: {
      type: String,
      trim: true,
      required: true,
    },
    ledgerAccountCodes: {
      type: Map,
      of: { type: mongoose.Schema.Types.ObjectId, ref: MODEL_NAMES.quickbooksAccounts },
      default: {},
    },
    reportSettings: {
      consolidatedAllAccounts: {
        type: Boolean,
        default: false,
      },
    },
  },
  { timestamps: true },
);

export const Bank = mongoose.model<IBank, IBankModel>(MODEL_NAMES.banks, BankSchema);
