import { Schema, model, Types } from 'mongoose';
import { toJSON, paginate } from '@/shared/utils/plugins';
import {
  LeadInterestType,
  LeadBuyingPreference,
} from '@/shared/constants/enum.constant';
import { ICaptureLeadDoc, ICaptureLeadModel } from './captureLead.interface';

const CaptureLeadSchema = new Schema<ICaptureLeadDoc>(
  {
    company: {
      type: Schema.Types.ObjectId,
      ref: 'Company',
    },
    name: { type: String, required: true },
    platform: { type: String, required: true },
    interestType: {
      type: String,
      enum: Object.values(LeadInterestType),
      default: LeadInterestType.BUY,
      required: true,
    },
    source: { type: Schema.Types.ObjectId, ref: 'Source', required: true },
    // Canonical status of the integration
    integrationStatus: {
      type: String,
      enum: ['pending', 'active', 'disabled', 'error'],
      default: 'active',
    },
    assignmentMode: {
      type: String,
      enum: ['equal', 'roundRobin', 'specificUser'],
      required: true,
      default: 'equal',
    },
    rrIndex: { type: Number, default: 0 },
    team: { type: Schema.Types.ObjectId, ref: 'Team' },
    assignedTo: [{ type: Schema.Types.ObjectId, ref: 'User', default: [] }],

    // Buy Lead Specific Fields
    buyingPreference: {
      type: String,
      enum: Object.values(LeadBuyingPreference),
      default: LeadBuyingPreference.PREFERRED_PROJECT,
    },
    project: { type: Schema.Types.ObjectId, ref: 'Project' },
    category: { type: Schema.Types.ObjectId, ref: 'Category' },
    configuration: [
      { type: Types.ObjectId, ref: 'Configuration', default: [] },
    ],
    propertyTypeBuy: [
      { type: Types.ObjectId, ref: 'SubCategory', default: [] },
    ],
    preferredState: { type: Schema.Types.ObjectId, ref: 'State' },
    preferredCity: { type: Schema.Types.ObjectId, ref: 'City' },
    preferredLocalities: [{ type: Types.ObjectId, ref: 'Area', default: [] }],
    isActive: { type: Boolean, default: true },
    isDeleted: { type: Boolean, default: false },
    deletedAt: { type: Date },
    deletedBy: { type: Schema.Types.ObjectId, ref: 'User' },
    // Audit
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
    googleAdsWebhookKey: { type: String },
  },
  { timestamps: true },
);

CaptureLeadSchema.plugin(toJSON);
CaptureLeadSchema.plugin(paginate);

export const CaptureLead = model<ICaptureLeadDoc, ICaptureLeadModel>(
  'CaptureLead',
  CaptureLeadSchema,
);
