import { logger } from '../utils/logger.js';

export const buildErrorQueueKey = (projectName) => `${projectName}_error_queue`;

export const enqueueError = async (client, queueKey, payload) => {
  try {
    await client.rPush(queueKey, JSON.stringify(payload));
  } catch (error) {
    logger.error('Redis enqueue error failed', { error: error?.message });
    throw error;
  }
};

export const startErrorRetryWorker = async ({
  client,
  queueKey,
  handler,
  redisIntegration,
  maxAttempts = 5
}) => {
  while (true) {
    const result = await client.blPop(queueKey, 0);
    const raw = result?.element;
    if (!raw) {
      continue;
    }
    let item;
    try {
      item = JSON.parse(raw);
    } catch (error) {
      logger.error('Invalid error payload', { error: error?.message });
      await redisIntegration.error('Invalid error payload', { module: 'redis', stack: error?.message });
      continue;
    }
    const attempts = item.attempts || 0;
    try {
      await handler(item);
    } catch (error) {
      logger.error('Retry handler failed', { error: error?.message, stack: error?.stack });
      const nextPayload = {
        ...item,
        attempts: attempts + 1,
        lastError: error?.message,
        lastAttemptAt: Date.now()
      };
      if (nextPayload.attempts >= maxAttempts) {
        await redisIntegration.error('Retry attempts exceeded', { module: 'retry', stack: JSON.stringify(nextPayload) });
      } else {
        await enqueueError(client, queueKey, nextPayload);
      }
    }
  }
};
