import {
  redisSubscriber,
  REDIS_TRANSFER_CHANNEL
} from "../../config/redis/redis";
import { collectionLog } from "../serviceLog";
import collectionPayoutsService from "./services/collectionPayouts.service";


let isProcessing = false;
let isPending = false;

const processQueue = async () => {
  if (isProcessing) {
    isPending = true;
    return;
  }

  isProcessing = true;

  try {
    do {
      isPending = false;

      await collectionPayoutsService.processPendingPayouts();

    } while (isPending);

  } catch (error: any) {
    collectionLog.info(`Collection Payout Worker Error: ${error?.message || error}`);
  } finally {
    isProcessing = false;
  }
};

const startCollectionPayoutWorker = async () => {
  try {

    // Connect Redis if not already connected
    if (!redisSubscriber.isOpen) {
      await redisSubscriber.connect();
    }

    await redisSubscriber.subscribe(
      REDIS_TRANSFER_CHANNEL,
      async (message) => {
        collectionLog.info(`Collection Payout Redis Event Received: ${message}`);

        await processQueue();
        collectionLog.info(
                `Redis [${REDIS_TRANSFER_CHANNEL}] waiting........`
            );
      }
    );

    collectionLog.info("Collection Payout Worker Started");

    // Process pending payouts on startup
    await processQueue();
     collectionLog.info(
                `Redis [${REDIS_TRANSFER_CHANNEL}] waiting........`
            );

  } catch (error: any) {
    collectionLog.info(`Collection Payout Worker Startup Error: ${error?.message || error}`);
  }
};

startCollectionPayoutWorker();