import { Processor, WorkerHost } from "@nestjs/bullmq";
import { Inject, Injectable } from "@nestjs/common";
import type { Job } from "bullmq";
import { Logger } from "nestjs-pino";
import { QUEUE_NAMES } from "@bff/infra/queue/queue.constants";
import { FreebitOrchestratorService } from "@bff/integrations/freebit/services/freebit-orchestrator.service";
import { getErrorMessage } from "@bff/core/utils/error.util";
import {
  SIM_MANAGEMENT_JOB_NAMES as JOB_NAMES,
  type NetworkTypeChangeJob,
} from "./sim-management.queue";

@Processor(QUEUE_NAMES.SIM_MANAGEMENT)
@Injectable()
export class SimManagementProcessor extends WorkerHost {
  constructor(
    private readonly freebitService: FreebitOrchestratorService,
    @Inject(Logger) private readonly logger: Logger
  ) {
    super();
  }

  async process(job: Job<NetworkTypeChangeJob>): Promise<void> {
    switch (job.name) {
      case JOB_NAMES.NETWORK_TYPE_CHANGE:
        await this.handleNetworkTypeChange(job.data);
        return;
      default:
        this.logger.warn("Received unknown SIM management job", {
          jobName: job.name,
        });
    }
  }

  private async handleNetworkTypeChange(payload: NetworkTypeChangeJob): Promise<void> {
    try {
      await this.freebitService.updateSimFeatures(payload.account, {
        networkType: payload.networkType,
      });
      this.logger.log("Processed deferred network type change", {
        account: payload.account,
        subscriptionId: payload.subscriptionId,
        userId: payload.userId,
        networkType: payload.networkType,
      });
    } catch (error) {
      this.logger.error("Deferred network type change failed", {
        error: getErrorMessage(error),
        account: payload.account,
        subscriptionId: payload.subscriptionId,
        networkType: payload.networkType,
      });
      throw error;
    }
  }
}

