import type {
  SimActivationFeeCatalogItem,
  SimCatalogProduct,
} from "@customer-portal/domain/services";
import type { ActivationFeeDetails, OrderTotals } from "./types";

interface PriceContainer {
  oneTimePrice?: number | undefined;
  unitPrice?: number | undefined;
  monthlyPrice?: number | undefined;
}

export function getRequiredActivationFee(
  fees: SimActivationFeeCatalogItem[]
): SimActivationFeeCatalogItem | undefined {
  if (!Array.isArray(fees) || fees.length === 0) {
    return undefined;
  }
  return fees.find(fee => fee.catalogMetadata?.isDefault) || fees[0];
}

export function resolveOneTimeCharge(value?: PriceContainer | undefined): number {
  if (!value) return 0;
  return value.oneTimePrice ?? value.unitPrice ?? value.monthlyPrice ?? 0;
}

export function formatActivationFeeDetails(
  fee: SimActivationFeeCatalogItem | undefined,
  amount: number
): ActivationFeeDetails | undefined {
  if (!fee || amount <= 0) return undefined;
  return {
    name: fee.name,
    amount,
  };
}

export function calculateOrderTotals(
  plan: SimCatalogProduct,
  selectedAddonSkus: string[],
  addons: SimCatalogProduct[],
  activationFeeAmount: number
): OrderTotals {
  const monthlyTotal =
    (plan.monthlyPrice ?? 0) +
    selectedAddonSkus.reduce((sum, addonSku) => {
      const addon = addons.find(a => a.sku === addonSku);
      return sum + (addon?.monthlyPrice ?? 0);
    }, 0);

  const oneTimeTotal =
    (plan.oneTimePrice ?? 0) +
    activationFeeAmount +
    selectedAddonSkus.reduce((sum, addonSku) => {
      const addon = addons.find(a => a.sku === addonSku);
      return sum + (addon?.oneTimePrice ?? 0);
    }, 0);

  return { monthly: monthlyTotal, oneTime: oneTimeTotal };
}
