import { Schema, model } from 'mongoose';
import { toJSON, paginate } from '@/shared/utils/plugins';
import {
  IUnitBookingOrHoldDoc,
  IUnitBookingOrHoldModel,
} from './unitBookingOrHold.interface';

// Person sub-schema for documents
const PersonSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    aadharFront: {
      type: String,
      // required: true,
    },
    aadharBack: {
      type: String,
      // required: true,
    },
    panCard: {
      type: String,
      // required: true,
    },
    passportPhoto: {
      type: String,
      // required: true,
    },
    additionalDocs: [
      {
        type: String,
      },
    ],
  },
  { _id: false },
);

const unitBookingOrHoldSchema = new Schema<IUnitBookingOrHoldDoc>(
  {
    lead: {
      type: Schema.Types.ObjectId,
      ref: 'Lead',
    },
    contactId: {
      type: Schema.Types.ObjectId,
      ref: 'Contacts',
    },
    project: {
      type: Schema.Types.ObjectId,
      ref: 'Project',
    },
    property: {
      type: Schema.Types.ObjectId,
      ref: 'individualProperties',
    },
    unit: {
      type: Schema.Types.ObjectId,
      ref: 'Unit',
    },
    paymentPlan: {
      type: Schema.Types.ObjectId,
      ref: 'PaymentPlan',
    },
    soldBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    cpContact: {
      type: Schema.Types.ObjectId,
      ref: 'CPContact',
    },
    action: {
      type: String,
      enum: ['book', 'hold'],
      required: true,
    },
    comment: {
      type: String,
      trim: true,
    },
    holdUntil: {
      type: Date,
    },
    bookingAmount: {
      type: Number,
    },

    // Persons array of PersonSchema type, required only if action = book
    persons: {
      type: [PersonSchema],
      required: function (this: IUnitBookingOrHoldDoc) {
        return this.action === 'book';
      },
      default: undefined,
    },

    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    customFields: {
      type: Map,
      of: Schema.Types.Mixed,
      default: {},
    },
  },
  {
    timestamps: true,
  },
);

unitBookingOrHoldSchema.plugin(toJSON);
unitBookingOrHoldSchema.plugin(paginate);

export const UnitBookingOrHold = model<
  IUnitBookingOrHoldDoc,
  IUnitBookingOrHoldModel
>('UnitBookingOrHold', unitBookingOrHoldSchema);
