import { Injectable, Inject } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { FreebitFacade } from "@bff/integrations/freebit/facades/freebit.facade.js";
import { SimValidationService } from "../sim-validation.service.js";
import { extractErrorMessage } from "@bff/core/utils/error.util.js";
import type { SimDetails } from "@customer-portal/domain/sim";

@Injectable()
export class SimDetailsService {
  constructor(
    private readonly freebitService: FreebitFacade,
    private readonly simValidation: SimValidationService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Get SIM details for a subscription
   */
  async getSimDetails(userId: string, subscriptionId: number): Promise<SimDetails> {
    try {
      const { account } = await this.simValidation.validateSimSubscription(userId, subscriptionId);

      const simDetails = await this.freebitService.getSimDetails(account);

      this.logger.log(`Retrieved SIM details for subscription ${subscriptionId}`, {
        userId,
        subscriptionId,
        account,
        status: simDetails.status,
      });

      return simDetails;
    } catch (error) {
      const sanitizedError = extractErrorMessage(error);
      this.logger.error(`Failed to get SIM details for subscription ${subscriptionId}`, {
        error: sanitizedError,
        userId,
        subscriptionId,
      });
      throw error;
    }
  }

  /**
   * Get SIM details directly from Freebit without subscription validation
   * Useful for debugging specific accounts
   */
  async getSimDetailsDirectly(account: string): Promise<SimDetails> {
    try {
      this.logger.debug({ account }, "Querying Freebit for SIM details");

      const simDetails = await this.freebitService.getSimDetails(account);

      this.logger.debug(
        {
          account,
          planCode: simDetails.planCode,
          planName: simDetails.planName,
          status: simDetails.status,
          simType: simDetails.simType,
        },
        "Retrieved SIM details from Freebit"
      );

      return simDetails;
    } catch (error) {
      const sanitizedError = extractErrorMessage(error);
      this.logger.error({ error: sanitizedError, account }, "Failed to get SIM details");
      throw error;
    }
  }
}
