/**
 * Services Domain - Salesforce Provider Mapper
 *
 * Transforms Salesforce Product2 records to normalized services contracts.
 */

import type {
  CatalogProductBase,
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
  InternetAddonCatalogItem,
  SimCatalogProduct,
  SimActivationFeeCatalogItem,
  VpnCatalogProduct,
} from "../../contract.js";
import type {
  SalesforceProduct2WithPricebookEntries,
  SalesforcePricebookEntryRecord,
} from "./raw.types.js";
import {
  enrichInternetPlanMetadata,
  inferAddonTypeFromSku,
  inferInstallationTermFromSku,
} from "../../utils.js";

// ============================================================================
// Tier Templates (Hardcoded Product Metadata)
// ============================================================================

// ============================================================================
// Helper Functions
// ============================================================================

function coerceNumber(value: unknown): number | undefined {
  if (typeof value === "number") return value;
  if (typeof value === "string") {
    const parsed = Number.parseFloat(value);
    return Number.isFinite(parsed) ? parsed : undefined;
  }
  return undefined;
}

// ============================================================================
// Base Product Mapper
// ============================================================================

/**
 * Derive unit price from pricebook entry or product fields
 */
function deriveUnitPrice(
  pricebookEntry: SalesforcePricebookEntryRecord | undefined,
  product: SalesforceProduct2WithPricebookEntries
): number | undefined {
  return coerceNumber(pricebookEntry?.UnitPrice) ?? coerceNumber(product.Price__c);
}

/**
 * Derive and assign price fields to base product
 */
function assignPrices(
  base: CatalogProductBase,
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry: SalesforcePricebookEntryRecord | undefined
): void {
  const billingCycle = product.Billing_Cycle__c?.toLowerCase();
  const unitPrice = deriveUnitPrice(pricebookEntry, product);
  const monthlyField = coerceNumber(product.Monthly_Price__c);
  const oneTimeField = coerceNumber(product.One_Time_Price__c);

  if (unitPrice !== undefined) base.unitPrice = unitPrice;
  if (monthlyField !== undefined) base.monthlyPrice = monthlyField;
  if (oneTimeField !== undefined) base.oneTimePrice = oneTimeField;

  // Derive primary price fallback based on billing cycle
  const primaryPrice =
    coerceNumber(pricebookEntry?.UnitPrice) ??
    monthlyField ??
    coerceNumber(product.Price__c) ??
    oneTimeField;
  if (primaryPrice === undefined) return;

  const isMonthly = billingCycle === "monthly" || !billingCycle;
  if (isMonthly) {
    base.monthlyPrice = base.monthlyPrice ?? primaryPrice;
  } else {
    base.oneTimePrice = base.oneTimePrice ?? primaryPrice;
  }
}

function baseProduct(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): CatalogProductBase {
  const sku = product.StockKeepingUnit ?? "";
  const base: CatalogProductBase = {
    id: product.Id,
    sku,
    name: product.Name ?? sku,
  };

  if (product.Description) base.description = product.Description;
  if (product.Billing_Cycle__c) base.billingCycle = product.Billing_Cycle__c;
  if (typeof product.Catalog_Order__c === "number") base.displayOrder = product.Catalog_Order__c;

  assignPrices(base, product, pricebookEntry);

  return base;
}

// ============================================================================
// Internet Product Mappers
// ============================================================================

export function mapInternetPlan(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): InternetPlanCatalogItem {
  const base = baseProduct(product, pricebookEntry);
  const tier = product.Internet_Plan_Tier__c ?? undefined;
  const offeringType = product.Internet_Offering_Type__c ?? undefined;

  return enrichInternetPlanMetadata({
    ...base,
    internetPlanTier: tier,
    internetOfferingType: offeringType,
  });
}

export function mapInternetInstallation(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): InternetInstallationCatalogItem {
  const base = baseProduct(product, pricebookEntry);

  return {
    ...base,
    catalogMetadata: {
      installationTerm: inferInstallationTermFromSku(base.sku),
    },
  };
}

export function mapInternetAddon(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): InternetAddonCatalogItem {
  const base = baseProduct(product, pricebookEntry);
  const bundledAddonId = product.Bundled_Addon__c ?? undefined;
  const isBundledAddon = product.Is_Bundled_Addon__c ?? false;

  return {
    ...base,
    bundledAddonId,
    isBundledAddon,
    catalogMetadata: {
      addonType: inferAddonTypeFromSku(base.sku),
    },
  };
}

// ============================================================================
// SIM Product Mappers
// ============================================================================

export function mapSimProduct(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): SimCatalogProduct {
  const base = baseProduct(product, pricebookEntry);
  const dataSize = product.SIM_Data_Size__c ?? undefined;
  const planType = product.SIM_Plan_Type__c ?? undefined;
  const hasFamilyDiscount = product.SIM_Has_Family_Discount__c ?? false;
  const bundledAddonId = product.Bundled_Addon__c ?? undefined;
  const isBundledAddon = product.Is_Bundled_Addon__c ?? false;

  return {
    ...base,
    simDataSize: dataSize,
    simPlanType: planType,
    simHasFamilyDiscount: hasFamilyDiscount,
    bundledAddonId,
    isBundledAddon,
  };
}

export function mapSimActivationFee(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): SimActivationFeeCatalogItem {
  const simProduct = mapSimProduct(product, pricebookEntry);
  // Auto_Add__c and Is_Default__c are no longer in the query.
  // Default status is handled by SimServicesService fallback if not present.

  return {
    ...simProduct,
    catalogMetadata: {
      isDefault: false, // Will be handled by service fallback
    },
  };
}

// ============================================================================
// VPN Product Mapper
// ============================================================================

export function mapVpnProduct(
  product: SalesforceProduct2WithPricebookEntries,
  pricebookEntry?: SalesforcePricebookEntryRecord
): VpnCatalogProduct {
  const base = baseProduct(product, pricebookEntry);
  const vpnRegion = product.VPN_Region__c ?? undefined;

  return {
    ...base,
    vpnRegion,
  };
}

// ============================================================================
// PricebookEntry Extraction
// ============================================================================

export function extractPricebookEntry(
  record: SalesforceProduct2WithPricebookEntries
): SalesforcePricebookEntryRecord | undefined {
  const entries = record.PricebookEntries?.records;
  if (!Array.isArray(entries) || entries.length === 0) {
    return undefined;
  }

  // Return first active entry, or first entry if none are active
  const activeEntry = entries.find(e => e.IsActive === true);
  return activeEntry ?? entries[0];
}
