import QRCodeModel from '../models/QrCode';

class UpdateQrCodeStatus {
  private static queue: any[] = [];

  public static async CheckQrCodeStatus() {
    const cutoff = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);

    try {
      // Step 1: find old QR codes
      const docs = await (QRCodeModel as any)
        .find({ updated_at: { $lte: cutoff } })
        .populate('created_by')
        .lean()
        .exec();

      console.log(
        `[CheckQrCodeStatus] Found ${docs.length} QR codes older than 3 days.`
      );

      if (docs.length === 0) return [];

      // Step 2: push into in-memory queue
      this.queue.push(...docs);
      console.log(
        `[CheckQrCodeStatus] Queue initialized with ${this.queue.length} items.`
      );

      // Step 3: process the queue
      while (this.queue.length > 0) {
        const item = this.queue.shift();
        const user = item.created_by;
        const userInfo = user
          ? `${user.name || user.email || user._id}`
          : 'Unknown user';

        // Simulate sending notification
        await new Promise(resolve => {
          setTimeout(() => {
            console.log(
              `Sending notification for QRCode ID: ${item._id} to user: ${userInfo}`
            );
            resolve(null);
          }, 2000);
        });
      }

      console.log('[CheckQrCodeStatus] Finished processing queue.');

      return docs;
    } catch (err) {
      console.error('[CheckQrCodeStatus] error:', err);
      throw err;
    }
  }
}

export default UpdateQrCodeStatus;
