import mongoose from 'mongoose';

import { MODEL_NAMES } from './_models';

export interface IBankIntegrationAccount {
  integrationId: mongoose.Types.ObjectId;
  externalAccountId: string;
  name: string;
  accountNumber: string;
  accountType: string;
  currency: string;
  rawPayload: string;
  lastSyncAt: Date;
  currentBalance: number;
}

export type TBankIntegrationAccountCreate = Omit<IBankIntegrationAccount, 'integrationId'> & {
  integrationId: string;
};

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

export interface IBankIntegrationAccountLean extends IBankIntegrationAccount {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBankIntegrationAccountPlain extends Omit<IBankIntegrationAccount, 'integrationId'> {
  _id: string;
  integrationId: string;
  createdAt: Date;
  updatedAt: Date;
}

export type TBankIntegrationAccountModel = mongoose.Model<IBankIntegrationAccount>;

export const BankIntegrationAccountSchema = new mongoose.Schema<IBankIntegrationAccount, TBankIntegrationAccountModel>(
  {
    integrationId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.bankIntegrations,
    },
    externalAccountId: {
      type: String,
    },
    name: {
      type: String,
    },
    accountNumber: {
      type: String,
    },
    accountType: {
      type: String,
    },
    currency: {
      type: String,
    },
    rawPayload: {
      type: String,
    },
    lastSyncAt: {
      type: Date,
    },
    currentBalance: {
      type: Number,
    },
  },
  { timestamps: true },
);

BankIntegrationAccountSchema.index(
  { integrationId: 1, externalAccountId: 1 },
  { unique: true },
);

export const BankIntegrationAccount = mongoose.model<IBankIntegrationAccount, TBankIntegrationAccountModel>(MODEL_NAMES.bankIntegrationAccounts, BankIntegrationAccountSchema);
