import { Injectable, Inject, BadRequestException } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { FreebitOrchestratorService } from "@bff/integrations/freebit/services/freebit-orchestrator.service";
import { SimValidationService } from "./sim-validation.service";
import { SimNotificationService } from "./sim-notification.service";
import { getErrorMessage } from "@bff/core/utils/error.util";

@Injectable()
export class EsimManagementService {
  constructor(
    private readonly freebitService: FreebitOrchestratorService,
    private readonly simValidation: SimValidationService,
    private readonly simNotification: SimNotificationService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Reissue eSIM profile
   */
  async reissueEsimProfile(userId: string, subscriptionId: number, newEid?: string): Promise<void> {
    try {
      const { account } = await this.simValidation.validateSimSubscription(userId, subscriptionId);

      // First check if this is actually an eSIM
      const simDetails = await this.freebitService.getSimDetails(account);
      if (simDetails.simType !== "esim") {
        throw new BadRequestException("This operation is only available for eSIM subscriptions");
      }

      if (newEid) {
        if (!/^\d{32}$/.test(newEid)) {
          throw new BadRequestException("Invalid EID format. Expected 32 digits.");
        }
        await this.freebitService.reissueEsimProfileEnhanced(account, newEid, {
          oldEid: simDetails.eid,
          planCode: simDetails.planCode,
        });
      } else {
        await this.freebitService.reissueEsimProfile(account);
      }

      this.logger.log(`Successfully reissued eSIM profile for subscription ${subscriptionId}`, {
        userId,
        subscriptionId,
        account,
        oldEid: simDetails.eid,
        newEid: newEid || undefined,
      });

      await this.simNotification.notifySimAction("Reissue eSIM", "SUCCESS", {
        userId,
        subscriptionId,
        account,
        oldEid: simDetails.eid,
        newEid: newEid || undefined,
      });
    } catch (error) {
      const sanitizedError = getErrorMessage(error);
      this.logger.error(`Failed to reissue eSIM profile for subscription ${subscriptionId}`, {
        error: sanitizedError,
        userId,
        subscriptionId,
        newEid: newEid || undefined,
      });
      await this.simNotification.notifySimAction("Reissue eSIM", "ERROR", {
        userId,
        subscriptionId,
        newEid: newEid || undefined,
        error: sanitizedError,
      });
      throw error;
    }
  }
}
