import mongoose, { Document, Model } from 'mongoose';
import { MODEL_NAMES } from './_models';
import { IOrganization } from './Organization.model';

const mongooseLeanId = require('gemcap-be-common/plugins/id.plugin');

interface ISchemaItem {
  column: string;
  databaseTitle: string;
}

interface IMapSchema {
  data: ISchemaItem[];
  name: string;
  type: string;
}

export interface IBorrower {
  code: string;
  name: string;
  title: string;
  active: boolean;
  accrualStatus: boolean;
  organizationId: mongoose.Types.ObjectId;
  schemas: IMapSchema[];
}

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

export interface IBorrowerLean extends IBorrower {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IBorrowerPlain extends Omit<IBorrower, 'organizationId'> {
  _id: string;
  createdAt: Date;
  updatedAt: Date;
}

export type BorrowerModel = Model<IBorrowerDoc>;

export const BorrowerSchema = new mongoose.Schema(
  {
    code: {
      type: String,
      trim: true,
      required: true,
    },
    name: {
      type: String,
      trim: true,
      required: true,
    },
    title: {
      type: String,
      trim: true,
      required: true,
    },
    active: {
      type: Boolean,
      default: true,
    },
    accrualStatus: {
      type: Boolean,
      default: false,
    },
    organizationId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.organizations,
    },
    schemas: {
      required: false,
      type: [
        {
          name: {
            type: String,
            trim: true,
            required: true,
          },
          type: {
            type: String,
            trim: true,
            required: true,
          },
          data: [
            {
              column: {
                type: String,
                trim: true,
                required: true,
              },
              databaseTitle: {
                type: String,
                trim: true,
                required: true,
              },
            },
          ],
        },
      ],
      default: [],
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

BorrowerSchema.pre(/^(save)/, async function() {

});

BorrowerSchema.pre(/^(updateOne|updateMany|findOneAndUpdate)/, async function() {
});

BorrowerSchema.pre(/^(findOneAndDelete|deleteOne|deleteMany)/, async function() {
});

BorrowerSchema.plugin(mongooseLeanId);

export const BorrowerModel: mongoose.Model<IBorrowerDoc> = mongoose.model<IBorrowerDoc>(MODEL_NAMES.borrowers, BorrowerSchema);
