import { Inject, Injectable } from "@nestjs/common";
import { InjectQueue } from "@nestjs/bullmq";
import { Queue } from "bullmq";
import { Logger } from "nestjs-pino";
import { QUEUE_NAMES } from "@bff/infra/queue/queue.constants";

export type NetworkTypeChangeJob = {
  account: string;
  networkType: "4G" | "5G";
  userId: string;
  subscriptionId: number;
};

export const SIM_MANAGEMENT_JOB_NAMES = {
  NETWORK_TYPE_CHANGE: "network-type-change",
} as const;

@Injectable()
export class SimManagementQueueService {
  constructor(
    @InjectQueue(QUEUE_NAMES.SIM_MANAGEMENT) private readonly queue: Queue<NetworkTypeChangeJob>,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  async scheduleNetworkTypeChange(
    data: NetworkTypeChangeJob,
    delayMs = 30 * 60 * 1000
  ): Promise<void> {
    await this.queue.add(SIM_MANAGEMENT_JOB_NAMES.NETWORK_TYPE_CHANGE, data, {
      delay: delayMs,
      removeOnComplete: 100,
      removeOnFail: 50,
      attempts: 3,
      backoff: {
        type: "exponential",
        delay: 5000,
      },
      jobId: `${SIM_MANAGEMENT_JOB_NAMES.NETWORK_TYPE_CHANGE}:${data.account}:${Date.now()}`,
    });

    this.logger.log("Scheduled deferred SIM network type change", {
      account: data.account,
      subscriptionId: data.subscriptionId,
      userId: data.userId,
      networkType: data.networkType,
      delayMs,
    });
  }
}

