import { Inject, Injectable, NotFoundException } 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 {
  SalesforceProduct2Record,
  SalesforcePricebookEntryRecord,
} from "@customer-portal/domain/catalog";
import type { SalesforceResponse } from "@customer-portal/domain/common";
import {
  assertSalesforceId,
  buildInClause,
  sanitizeSoqlLiteral,
} from "@bff/integrations/salesforce/utils/soql.util";

export interface PricebookProductMeta {
  sku: string;
  pricebookEntryId: string;
  product2Id?: string;
  unitPrice?: number;
  itemClass?: string;
  internetOfferingType?: string;
  internetPlanTier?: string;
  vpnRegion?: string;
}

@Injectable()
export class OrderPricebookService {
  private readonly chunkSize = 100;

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

  async findPortalPricebookId(): Promise<string> {
    const name = this.configService.get<string>("PORTAL_PRICEBOOK_NAME")!;
    const soql = `SELECT Id, Name FROM Pricebook2 WHERE IsActive = true AND Name LIKE '%${sanitizeSoqlLiteral(name)}%' LIMIT 1`;

    try {
      const result = (await this.sf.query(soql, {
        label: "orders:pricebook:findPortal",
      })) as SalesforceResponse<{ Id?: string }>;
      if (result.records?.length) {
        const resolved = result.records[0]?.Id;
        if (resolved) {
          return assertSalesforceId(resolved, "pricebookId");
        }
      }

      const std = (await this.sf.query(
        "SELECT Id FROM Pricebook2 WHERE IsStandard = true AND IsActive = true LIMIT 1",
        { label: "orders:pricebook:findStandard" }
      )) as SalesforceResponse<{ Id?: string }>;

      const pricebookId = std.records?.[0]?.Id;
      if (!pricebookId) {
        this.logger.error({ soql }, "No active pricebook found");
        throw new NotFoundException("No active pricebook found");
      }

      return assertSalesforceId(pricebookId, "pricebookId");
    } catch (error) {
      this.logger.error({ error, soql }, "Failed to find pricebook");
      throw new NotFoundException("Failed to find pricebook");
    }
  }

  async fetchProductMeta(
    pricebookId: string,
    skus: string[]
  ): Promise<Map<string, PricebookProductMeta>> {
    const safePricebookId = assertSalesforceId(pricebookId, "pricebookId");
    const uniqueSkus = Array.from(
      new Set(skus.map(sku => sku?.trim()).filter((sku): sku is string => Boolean(sku)))
    );

    if (uniqueSkus.length === 0) {
      return new Map();
    }

    const meta = new Map<string, PricebookProductMeta>();

    for (let i = 0; i < uniqueSkus.length; i += this.chunkSize) {
      const slice = uniqueSkus.slice(i, i + this.chunkSize);
      const whereIn = buildInClause(slice, "skus");
      const soql =
        `SELECT Id, Product2Id, UnitPrice, ` +
        `Product2.StockKeepingUnit, ` +
        `Product2.Item_Class__c, ` +
        `Product2.Internet_Offering_Type__c, ` +
        `Product2.Internet_Plan_Tier__c, ` +
        `Product2.VPN_Region__c ` +
        `FROM PricebookEntry ` +
        `WHERE Pricebook2Id='${safePricebookId}' AND IsActive=true AND Product2.StockKeepingUnit IN ${whereIn}`;

      try {
        const res = (await this.sf.query(soql, {
          label: "orders:pricebook:fetchProducts",
        })) as SalesforceResponse<
          SalesforcePricebookEntryRecord & { Product2?: SalesforceProduct2Record | null }
        >;

        for (const record of res.records ?? []) {
          const product = record.Product2 ?? undefined;
          const sku = product?.StockKeepingUnit ?? undefined;
          if (!sku) continue;

          const normalizedSku = sku.trim().toUpperCase();
          meta.set(normalizedSku, {
            sku,
            pricebookEntryId: assertSalesforceId(record.Id ?? undefined, "pricebookEntryId"),
            product2Id: record.Product2Id ?? undefined,
            unitPrice: typeof record.UnitPrice === "number" ? record.UnitPrice : undefined,
            itemClass: product?.Item_Class__c ?? undefined,
            internetOfferingType: product?.Internet_Offering_Type__c ?? undefined,
            internetPlanTier: product?.Internet_Plan_Tier__c ?? undefined,
            vpnRegion: product?.VPN_Region__c ?? undefined,
          });
        }
      } catch (error) {
        this.logger.error({ error, slice }, "Failed to fetch pricebook entries by SKU");
        throw error;
      }
    }

    return meta;
  }
}
