import { Injectable, Inject } 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 { getErrorMessage } from "@bff/core/utils/error.util";
import type { SimDetails } from "@customer-portal/domain/sim";

@Injectable()
export class SimDetailsService {
  constructor(
    private readonly freebitService: FreebitOrchestratorService,
    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 = getErrorMessage(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.log(`[DEBUG] Querying Freebit for account: ${account}`);

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

      this.logger.log(`[DEBUG] Retrieved SIM details from Freebit`, {
        account,
        planCode: simDetails.planCode,
        planName: simDetails.planName,
        status: simDetails.status,
        simType: simDetails.simType,
      });

      return simDetails;
    } catch (error) {
      const sanitizedError = getErrorMessage(error);
      this.logger.error(`[DEBUG] Failed to get SIM details for account ${account}`, {
        error: sanitizedError,
        account,
      });
      throw error;
    }
  }
}
