import dayjs from 'dayjs';
import { NotificationJobType } from '../notifications/notification.job';
import { UserType } from '@/shared/constants/enum.constant';

import { Company } from '@/modules/company/company.model'; // <-- use company model
import { EmailData, processNotificationJob } from './sendTrasactionEmail';
import { batches, buildEmailBatch } from '../helper/EmailDataHelper';

export const FetchNotifyEmail = async () => {
  const pipeLine = [
    {
      $lookup: {
        from: 'users',
        let: { companyId: '$_id' },
        pipeline: [
          {
            $match: {
              $expr: { $eq: ['$$companyId', '$company.id'] },
            },
          },
          {
            $match: { userType: UserType.ADMIN }, // admin filter
          },
        ],
        as: 'users',
      },
    },
    {
      $match: {
        planExpiryDate: {
          $gte: dayjs().toDate(),
          $lte: dayjs().add(7, 'days').toDate(),
        },
      },
    },
    // optional: only companies with at least one admin
    {
      $match: {
        'users.0': { $exists: true },
      },
    },
  ];

  console.log('pipeline', JSON.stringify(pipeLine));
  const cursor = Company.aggregate(pipeLine).cursor({ batchSize: 500 }); // <-- note Company here
  let batch: unknown[] = [];

  for await (const doc of cursor) {
    batch.push(doc);

    if (batch.length >= 500) {
      let processedBatch = buildEmailBatch(batch as batches[]);

      processNotificationJob(
        NotificationJobType.SEND_EMAIL,
        processedBatch as EmailData[],
      );
      batch = [];
    }
  }
  if (batch.length > 0) {
    let processedBatch = buildEmailBatch(batch as batches[]);

    processNotificationJob(
      NotificationJobType.SEND_EMAIL,
      processedBatch as EmailData[],
    );
  }
};
