import { Schema, model } from 'mongoose';
import { paginate, toJSON } from '@/shared/utils/plugins/index';
import { ILeadStageDoc, ILeadStageModel } from '@/modules/master/leadStage/leadStage.interface';

const leadStageSchema = new Schema<ILeadStageDoc>(
  {
    stageName: { type: String, required: true, trim: true },
    description: { type: String, trim: true },
    color: { type: String, required: true },
    position: { type: Number, min: 1 },
    isDefault: { type: Boolean, default: false },
    company: { type: Schema.Types.ObjectId, ref: 'Company', required: true},
    isActive: { type: Boolean, default: true },
    isProtected:{ type: Boolean, default: false },
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  {
    timestamps: true,
  },
);

leadStageSchema.pre<ILeadStageDoc>('save', async function (next) {
  // eslint-disable-next-line curly
  if (this.isNew && this.position === undefined) {
    try {
      const lastStage = await (this.constructor as ILeadStageModel).findOne({ company: this.company,isDefault: this.isDefault }).sort({ position: -1 }).limit(1);
      this.position = lastStage ? lastStage.position + 1 : 1;
      next();
    } catch (error) {
      next(error);
    }
  } else if (this.isNew && this.position !== undefined)
    next(); 
  else
    next();
});

// leadStageSchema.index({ company: 1 }, { unique: true });

leadStageSchema.plugin(toJSON);
leadStageSchema.plugin(paginate);

export const LeadStage = model<ILeadStageDoc, ILeadStageModel>('LeadStage', leadStageSchema);