import { nanoid } from 'nanoid';

import logger from '../libs/logger';
import createQueue from '../libs/queue';
import { runArchiveJob } from '../libs/archive/executor';

export type ArchiveQueueJob = {
  tables?: string[];
  dryRun?: boolean;
  triggeredBy: 'cron' | 'manual';
  triggeredByUserId?: string;
};

export const archiveQueue = createQueue<ArchiveQueueJob>({
  name: 'archive',
  onJob: (job) => runArchiveJob(job),
  options: {
    concurrency: 1,
    maxRetries: 1,
  },
});

export const enqueueArchiveJob = (job: ArchiveQueueJob) => {
  const id = nanoid();
  archiveQueue.push({ id, job, persist: false });
  logger.info('archive job queued', { id, job });
  return id;
};

archiveQueue.on('failed', ({ id, job, error }) => {
  logger.error('archive job failed', { id, job, error });
});
