import mongoose from 'mongoose';
import Joi from 'joi';

import { MODEL_NAMES } from './_models';
import { ILoanBrokerWithId } from './LoanBroker.model';

export const ProductBrokerValidationSchema = Joi.object({
  _id: Joi.string().required(),
  order: Joi.number(),
  borrowerId: Joi.string().required(),
  active: Joi.boolean().required(),
  loanBrokerId: Joi.string().required(),
  BSCode: Joi.string().required(),
  PLCode: Joi.string().required(),
  productId: Joi.string().required(),
  interestShare: Joi.number().required(),
  adminShare: Joi.number().required(),
  otherShare: Joi.number().required(),
});

export interface IProductBroker {
  order: number;
  borrowerId: mongoose.Types.ObjectId;
  active: boolean;
  loanBrokerId: mongoose.Types.ObjectId;
  BSCode: string;
  PLCode: string;
  productId: mongoose.Types.ObjectId;
  interestShare: number;
  adminShare: number;
  otherShare: number;
}

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

export interface IProductBrokerLean extends IProductBroker {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IProductBrokerPlain extends Omit<IProductBroker, 'borrowerId' | 'loanBrokerId' | 'productId'> {
  _id: string;
  borrowerId: string;
  loanBrokerId: string;
  productId: string;
}

export interface IProductBrokerDocWithBroker extends IProductBrokerDoc {
  loanBroker: ILoanBrokerWithId;
}

export type IProductBrokerView = Omit<IProductBrokerLean, 'borrowerId' | 'order'>

export type TProductBrokerModel = mongoose.Model<IProductBroker>;

export const ProductBrokerSchema = new mongoose.Schema(
  {
    borrowerId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.borrowers,
      required: true,
    },
    order: {
      type: Number,
      required: true,
    },
    active: {
      type: Boolean,
      required: true,
    },
    loanBrokerId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanBrokers,
      required: true,
    },
    BSCode: {
      type: String,
      required: true,
      trim: true,
    },
    PLCode: {
      type: String,
      required: true,
      trim: true,
    },
    productId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.loanProducts,
      required: true,
    },
    interestShare: {
      type: Number,
      required: true,
    },
    adminShare: {
      type: Number,
      required: true,
    },
    otherShare: {
      type: Number,
      required: true,
    },
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const ProductBrokerModel: mongoose.Model<IProductBrokerDoc> = mongoose.model<IProductBrokerDoc>(MODEL_NAMES.productBrokers, ProductBrokerSchema);
