import { Schema, model } from 'mongoose';
import { paginate, toJSON } from '@/shared/utils/plugins';
import { IActivityDoc, IActivityModel } from './activity.interface';
import { ActivityStatus, ActivityType } from '@/shared/constants/enum.constant';

const activitySchema = new Schema<IActivityDoc>(
  {
    lead: {
      type: Schema.Types.ObjectId,
      ref: 'Lead',
    },
    contact: {
      type: Schema.Types.ObjectId,
      ref: 'Contact',
    },
    task: {
      type: Schema.Types.ObjectId,
      ref: 'Tasks',
    },
    company: {
      type: Schema.Types.ObjectId,
      ref: 'Company',
    },
    project: {
      type: Schema.Types.ObjectId,
      ref: 'Project',
    },
    property: {
      type: Schema.Types.ObjectId,
      ref: 'individualProperties',
    },
    unit: {
      type: Schema.Types.ObjectId,
      ref: 'Unit',
    },
    unitBookingOrHold: {
      type: Schema.Types.ObjectId,
      ref: 'UnitBookingOrHold',
    },
    files: [
      {
        type: Schema.Types.ObjectId,
        ref: 'File',
      },
    ],
    quotationFile: {
      type: String,
    },
    price: {
      type: Number,
    },
    total: {
      type: Number,
    },
    title: {
      type: String,
      required: true,
      trim: true,
    },
    comment: {
      type: String,
      trim: true,
      default: '',
    },
    type: {
      type: String,
      enum: Object.values(ActivityType),
      required: true,
    },
    assignedTo: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    status: {
      type: String,
      enum: Object.values(ActivityStatus),
      default: ActivityStatus.PENDING,
    },
    scheduleDateTime: {
      type: String,
      default: null,
    },
    location: {
      type: String,
    },
    completionNote: {
      type: String,
    },
    duration: {
      type: Number,
    },
    audioFileName: {
      type: String,
    },
    myoperatorReferenceId: {
      type: String,
      trim: true,
      default: null,
    },
    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  },
);

activitySchema.plugin(toJSON);
activitySchema.plugin(paginate);

// Index for lookup queries from leads (prevents COLLSCAN in countLeadsWithoutActivity)
activitySchema.index({ lead: 1, title: 1 });

// Additional index for better performance on activity queries
activitySchema.index({ lead: 1, createdAt: -1 });

export const Activity = model<IActivityDoc, IActivityModel>(
  'Activity',
  activitySchema,
);
