import mongoose from 'mongoose';

import { MODEL_NAMES } from './_models';

export interface IBankIntegrationTransaction {
  accountId: mongoose.Types.ObjectId;
  externalTransactionId: string;
  amount: number;
  currency: string;
  postedAt: Date;
  type: string;
  status: string;
  rawPayload: string;
  syncedAt: Date;
  text: string;
  description: string;
}

export type TBankIntegrationTransactionCreate = Omit<IBankIntegrationTransaction, 'accountId'> & {
  accountId: string;
};

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

export interface IBankIntegrationTransactionLean extends IBankIntegrationTransaction {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBankIntegrationTransactionPlain extends Omit<IBankIntegrationTransaction, 'accountId'> {
  _id: string;
  accountId: string;
  createdAt: Date;
  updatedAt: Date;
}

export type TBankIntegrationTransactionModel = mongoose.Model<IBankIntegrationTransaction>;

export const BankIntegrationTransactionSchema = new mongoose.Schema<IBankIntegrationTransaction, TBankIntegrationTransactionModel>(
  {
    accountId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.bankIntegrationAccounts,
    },
    externalTransactionId: {
      type: String,
    },
    amount: {
      type: Number,
    },
    currency: {
      type: String,
    },
    postedAt: {
      type: Date,
    },
    type: {
      type: String,
    },
    status: {
      type: String,
    },
    rawPayload: {
      type: String,
    },
    text: {
      type: String,
    },
    description: {
      type: String,
    },
    syncedAt: {
      type: Date,
    },
  },
  { timestamps: true },
);

BankIntegrationTransactionSchema.index(
  { accountId: 1, externalTransactionId: 1 },
  { unique: true },
);

export const BankIntegrationTransaction = mongoose.model<IBankIntegrationTransaction, TBankIntegrationTransactionModel>(MODEL_NAMES.bankIntegrationTransactions, BankIntegrationTransactionSchema);
