import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { catchError, lastValueFrom } from 'rxjs';
import { DispoLiveApiExtractorsService } from '../../feat-extractors/dispo-live-api-extractors.service';
import { SCHICHTPLANUNG_QUEUE } from '../tokens';

@Processor(SCHICHTPLANUNG_QUEUE, {
  limiter: {
    duration: 300,
    max: 1,
  },
})
export class SchichtplanungConsumer extends WorkerHost {
  private readonly logger = new Logger(SchichtplanungConsumer.name);

  constructor(private readonly dlApiService: DispoLiveApiExtractorsService) {
    super();
  }

  async process(job: Job, token?: string): Promise<any> {
    try {
      switch (job.name) {
        case 'Create':
          return await lastValueFrom(
            this.dlApiService.fahrzeugplanungAdd(job.data),
          );
        case 'Update':
          return await lastValueFrom(
            this.dlApiService.fahrzeugplanungUpdate(job.data).pipe(
              catchError((err) => {
                throw err?.response?.data ?? err;
              }),
            ),
          );
        case 'Delete':
          return await lastValueFrom(
            this.dlApiService.fahrzeugplanungDelete(job.data),
          );
        default:
          throw new Error(
            `[${SchichtplanungConsumer.name}]: job name not implemented ${job.name}`,
          );
      }
    } catch (error) {
      this.logger.error(
        `job processing failed, ${typeof error === 'object' ? JSON.stringify(error) : error}, ${JSON.stringify(job.data)}`,
      );
    }
  }
}
