import { Schema } from 'mongoose';
import { paginate, toJSON } from '@/shared/utils/plugins/index.js';
import { salesBaseSchema } from '@/modules/customer/schema/sale.schema';
import { ICustomerDoc } from '@/modules/customer/customer.interface';
import { CUSTOMER_DOCUMENT_STATUS } from '../customer.constant';

export const customerSchema = new Schema<ICustomerDoc>(
  {
    company: { type: Schema.Types.ObjectId, ref: 'Company' },
    unitBookingOrHold: {
      type: Schema.Types.ObjectId,
      ref: 'UnitBookingOrHold',
    },
    paymentPlan: {
      type: Schema.Types.ObjectId,
      ref: 'PaymentPlan',
    },
    propertyTitle: { type: String },
    name: { type: String },
    email: { type: String },
    phone: { type: Number },
    contactId: { type: Schema.Types.ObjectId, ref: 'Contact' },
    leadId: { type: Schema.Types.ObjectId, ref: 'Lead' },
    sales: [salesBaseSchema],
    bookingStatus: {
      type: String,
      enum: ['active', 'cancelled'],
      default: 'active',
    },
    cancellationDetails: {
      cancelledAt: { type: Date },
      cancelledBy: { type: Schema.Types.ObjectId, ref: 'User' },
      reason: { type: String },
    },
    documents: [
      {
        document: {
          type: Schema.Types.ObjectId,
          ref: 'Documents',
          required: true,
        },

        status: {
          type: String,
          enum: Object.values(CUSTOMER_DOCUMENT_STATUS),
          default: CUSTOMER_DOCUMENT_STATUS.NOT_GENERATED,
        },
        url: { type: String },

        generatedAt: { type: Date },
        generatedBy: { type: Schema.Types.ObjectId, ref: 'User' },

        sentAt: { type: Date },
        sentBy: { type: Schema.Types.ObjectId, ref: 'User' },
      },
    ],
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  },

  {
    timestamps: true,
    discriminatorKey: 'kind',
  },
);

customerSchema.index({ _id: 1, 'documents.document': 1 }, { unique: true });

// add plugin that converts mongoose to json
customerSchema.plugin(toJSON);
customerSchema.plugin(paginate);
