/**
 * Salesforce Catalog Query Builders
 *
 * SOQL query builders for Product2 catalog queries.
 * Extracted from BaseCatalogService for consistency with order query builders.
 */
import { sanitizeSoqlLiteral, assertSoqlFieldName } from "./soql.util";

/**
 * Build base product query with optional filtering
 */
export function buildProductQuery(
  portalPricebookId: string,
  portalCategoryField: string,
  category: string,
  itemClass: string,
  additionalFields: string[] = [],
  additionalConditions: string = ""
): string {
  const categoryField = assertSoqlFieldName(portalCategoryField, "PRODUCT_PORTAL_CATEGORY_FIELD");
  const baseFields = ["Id", "Name", "StockKeepingUnit", categoryField, "Item_Class__c"];
  const allFields = [...baseFields, ...additionalFields].join(", ");

  const safeCategory = sanitizeSoqlLiteral(category);
  const safeItemClass = sanitizeSoqlLiteral(itemClass);

  return `
    SELECT ${allFields},
           (SELECT Id, UnitPrice, Pricebook2Id, Product2Id, IsActive 
            FROM PricebookEntries 
            WHERE Pricebook2Id = '${portalPricebookId}' 
            AND IsActive = true 
            LIMIT 1)
    FROM Product2 
    WHERE ${categoryField} = '${safeCategory}'
    AND Item_Class__c = '${safeItemClass}'
    AND Portal_Accessible__c = true
    ${additionalConditions}
    ORDER BY Catalog_Order__c NULLS LAST, Name
  `;
}

/**
 * Build catalog service query (Service items only)
 */
export function buildCatalogServiceQuery(
  portalPricebookId: string,
  portalCategoryField: string,
  category: string,
  additionalFields: string[] = []
): string {
  return buildProductQuery(
    portalPricebookId,
    portalCategoryField,
    category,
    "Service",
    additionalFields,
    `AND Portal_Catalog__c = true`
  );
}

/**
 * Build query for specific account eligibility check
 */
export function buildAccountEligibilityQuery(sfAccountId: string): string {
  return `
    SELECT Id, Internet_Eligibility__c 
    FROM Account 
    WHERE Id = '${sfAccountId}' 
    LIMIT 1
  `;
}
