/**
 * Catalog Domain - Salesforce Provider Mapper
 * 
 * Transforms Salesforce Product2 records to normalized catalog contracts.
 */

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

// ============================================================================
// 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;
}

function inferInstallationTypeFromSku(sku: string): "One-time" | "12-Month" | "24-Month" {
  const normalized = sku.toLowerCase();
  if (normalized.includes("24")) return "24-Month";
  if (normalized.includes("12")) return "12-Month";
  return "One-time";
}

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

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

  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;

  // Derive prices
  const billingCycle = product.Billing_Cycle__c?.toLowerCase();
  const unitPriceFromPricebook = coerceNumber(pricebookEntry?.UnitPrice);
  const priceField = coerceNumber(product.Price__c);
  const monthlyField = coerceNumber(product.Monthly_Price__c);
  const oneTimeField = coerceNumber(product.One_Time_Price__c);

  if (unitPriceFromPricebook !== undefined) {
    base.unitPrice = unitPriceFromPricebook;
  } else if (priceField !== undefined) {
    base.unitPrice = priceField;
  }

  if (monthlyField !== undefined) {
    base.monthlyPrice = monthlyField;
  }

  if (oneTimeField !== undefined) {
    base.oneTimePrice = oneTimeField;
  }

  const primaryPrice =
    unitPriceFromPricebook ?? monthlyField ?? priceField ?? oneTimeField;

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

  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: {
      ...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: {
      ...base.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);
  const isDefault = product.Is_Default__c === true;
  const autoAdd = product.Auto_Add__c === true;

  return {
    ...simProduct,
    catalogMetadata: {
      ...(simProduct.catalogMetadata ?? {}),
      isDefault,
      autoAdd,
    },
  };
}

// ============================================================================
// 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];
}
