import mongoose from 'mongoose';

import { MODEL_NAMES } from './_models';

export interface IFacility {
  uiId: string;
  borrowerId: mongoose.Types.ObjectId;
  name: string;
  order: number;
  deletedAt?: Date;
}

export type TFacilityDoc = mongoose.HydratedDocument<IFacility>;

export interface IFacilityLean extends IFacility {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IFacilityPlain extends Omit<IFacility, 'borrowerId'> {
  _id: string;
  borrowerId: string;
  createdAt: Date;
  updatedAt: Date;
}

export type TFacilityModel = mongoose.Model<IFacility>;

export const FacilitySchema = new mongoose.Schema<IFacility, TFacilityModel>(
  {
    borrowerId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.borrowers,
      required: true,
    },
    uiId: {
      type: String,
      required: true,
    },
    name: {
      type: 'String',
      required: true,
    },
    order: {
      type: Number,
      required: true,
    },
    deletedAt: {
      type: Date,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

FacilitySchema.index(
  { borrowerId: 1, name: 1 },
  { unique: true },
);

export const Facility = mongoose.model<IFacility, TFacilityModel>(MODEL_NAMES.facilities, FacilitySchema);
