import mongoose from 'mongoose';
import dayjs from 'dayjs';

import { MODEL_NAMES } from './_models';
import { ILoanChargeDoc } from './LoanCharges.model';

export interface IStatementPeriod {
  start: dayjs.Dayjs;
  end: dayjs.Dayjs;
}

export const LOAN_STATEMENT_TRANSACTION_FIELDS = [
  '_id',
  'date',
  'chargeId',
  'amount',
  'amountPaid',
  'balance',
  'isSystem',
  'memo',
  'userId',
];

export interface ILoanStatementTransaction {
  order: number;
  date: Date;
  chargeId: mongoose.Types.ObjectId;
  amount: number;
  amountPaid?: number;
  balance?: number;
  isSystem: boolean;
  memo: string;
  settlementCode?: string;
  userId?: string;
  isEditable?: boolean;
}

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

export interface ILoanStatementTransactionLean extends ILoanStatementTransaction {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface ILoanStatementTransactionPlain extends Omit<ILoanStatementTransaction, 'chargeId'> {
  _id: string;
  chargeId: string;
}

export interface ILoanStatementTransactionWithId extends ILoanStatementTransaction {
  _id: mongoose.Types.ObjectId;
}

export interface ILoanStatementTransactionDocWithCharge extends ILoanStatementTransactionDoc {
  charge: ILoanChargeDoc;
}

export type ILoanStatementTransactionView = Omit<ILoanStatementTransactionWithId, 'order'>

export type TLoanStatementTransactionModel = mongoose.Model<ILoanStatementTransaction>;

export const LoanStatementSchema = new mongoose.Schema(
  {
    order: {
      type: Number,
      required: true,
      default: 0,
    },
    date: {
      type: Date,
      required: true,
    },
    chargeId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanCharges,
      required: true,
    },
    amount: {
      type: Number,
      required: true,
    },
    amountPaid: {
      type: Number,
      required: false,
    },
    balance: {
      type: Number,
      required: false,
    },
    isSystem: {
      type: Boolean,
      default: true,
    },
    memo: {
      type: String,
    },
    settlementCode: {
      type: String,
    },
    userId: {
      type: String,
      required: false,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const LoanStatementTransactionModel: mongoose.Model<ILoanStatementTransactionDoc> = mongoose.model<ILoanStatementTransactionDoc>(MODEL_NAMES.loanStatements, LoanStatementSchema);
