import { Lead } from '@/modules/lead/lead.model';
import { updateLeadScoreFromActivity } from '@/modules/leadScore/leadScore.service';
import dayjs from 'dayjs';
import { Types } from 'mongoose';

const INACTIVITY_DAYS = 7;

export const updateLeadScore = async () => {
  try {
    const cutoffDate = dayjs().subtract(INACTIVITY_DAYS, 'day').toDate();

    // Find leads not updated in the last `INACTIVITY_DAYS`
    const inactiveLeads = await Lead.find({
      updatedAt: { $lte: cutoffDate },
    }).select('_id');

    console.log(`Found ${inactiveLeads.length} inactive leads to update`);

    // Use Promise.all to update all leads in parallel
    await Promise.all(
      inactiveLeads.map((lead) =>
        updateLeadScoreFromActivity(
          'communication_penalty',
          lead._id as Types.ObjectId,
        ),
      ),
    );
  } catch (error) {
    console.error('Error updating lead scores:', error);
  }
};
