import { Injectable, Inject } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Logger } from "nestjs-pino";
import { SalesforceConnection } from "@bff/integrations/salesforce/services/salesforce-connection.service";
import type {
  SimTopUpPricing,
  SimTopUpPricingPreviewResponse,
} from "@customer-portal/domain/sim";
import type { SalesforceResponse } from "@customer-portal/domain/common";
import { sanitizeSoqlLiteral } from "@bff/integrations/salesforce/utils/soql.util";

@Injectable()
export class SimTopUpPricingService {
  constructor(
    private readonly sf: SalesforceConnection,
    private readonly configService: ConfigService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Get SIM top-up pricing configuration from Salesforce Product2
   * Looks for a product with SKU matching TOP_UP_PRICING_SKU or similar
   */
  async getTopUpPricing(): Promise<SimTopUpPricing> {
    try {
      // Query Salesforce for top-up pricing configuration
      // Adjust this query based on your actual Salesforce schema
      const pricingSku = this.configService.get<string>("SIM_TOPUP_PRICING_SKU") || "SIM_TOPUP_DATA";
      
      const soql = `
        SELECT 
          Id, 
          ProductCode,
          Data_Price_Per_GB_JPY__c,
          Min_Quota_MB__c,
          Max_Quota_MB__c
        FROM Product2 
        WHERE ProductCode = '${sanitizeSoqlLiteral(pricingSku)}'
        AND IsActive = true
        LIMIT 1
      `;

      interface PricingRecord {
        Data_Price_Per_GB_JPY__c?: number;
        Min_Quota_MB__c?: number;
        Max_Quota_MB__c?: number;
      }

      const result = (await this.sf.query(soql, {
        label: "sim-topup:pricing:get",
      })) as SalesforceResponse<PricingRecord>;

      if (result.records && result.records.length > 0) {
        const record = result.records[0];
        return {
          pricePerGbJpy: record?.Data_Price_Per_GB_JPY__c || 500, // fallback to 500
          minQuotaMb: record?.Min_Quota_MB__c || 1000, // 1GB min
          maxQuotaMb: record?.Max_Quota_MB__c || 51200, // 50GB max
          currency: "JPY",
        };
      }

      // Fallback to default pricing if not found in Salesforce
      this.logger.warn("SIM top-up pricing not found in Salesforce, using defaults");
      return this.getDefaultPricing();
    } catch (error) {
      this.logger.error("Failed to fetch SIM top-up pricing from Salesforce", { error });
      return this.getDefaultPricing();
    }
  }

  /**
   * Calculate pricing preview for a given quota
   */
  async calculatePricingPreview(quotaMb: number): Promise<SimTopUpPricingPreviewResponse> {
    const pricing = await this.getTopUpPricing();
    const quotaGb = quotaMb / 1000;
    const totalPriceJpy = Math.ceil(quotaGb) * pricing.pricePerGbJpy;

    return {
      quotaMb,
      quotaGb,
      totalPriceJpy,
      pricePerGbJpy: pricing.pricePerGbJpy,
      currency: pricing.currency,
    };
  }

  private getDefaultPricing(): SimTopUpPricing {
    return {
      pricePerGbJpy: 500,
      minQuotaMb: 1000, // 1GB
      maxQuotaMb: 51200, // 50GB
      currency: "JPY",
    };
  }
}

