import { Discount, Tariff, findDiscountFactor } from "@frontend/kitui"
import { calcCart } from "./calcCart/calcCart"

export function calcIndividualTariffPrices(
	tariff: Tariff,
	discounts: Discount[],
	purchasesAmount: number,
	currentTariffs: Tariff[],
	isUserNko?: boolean,
): {
  priceBeforeDiscounts: number;
  priceAfterDiscounts: number;
} {
	const priceBeforeDiscounts =
    tariff.price || tariff.privileges.reduce((sum, privilege) => sum + privilege.amount * privilege.price, 0)
	let priceAfterDiscounts = 0

	const cart = calcCart([...currentTariffs, tariff], discounts, purchasesAmount, isUserNko)
  console.log('CITP', cart)
  if (cart.allAppliedDiscounts[0]?.Target.Overhelm) return {priceBeforeDiscounts: priceBeforeDiscounts, priceAfterDiscounts: priceBeforeDiscounts * cart.allAppliedDiscounts[0].Target.Factor }
   cart.services.forEach(s => {
     if (s.serviceKey === tariff.privileges[0].serviceKey) {
       let processed = false
       s.tariffs.forEach(t => {
         if (t.id === tariff._id && !processed) {
           processed = true
            t.privileges.forEach(p => priceAfterDiscounts+=p.price)
         }
       })
     }
   })
   priceAfterDiscounts*=findDiscountFactor(cart.appliedLoyaltyDiscount)
   priceAfterDiscounts*=findDiscountFactor(cart.appliedCartPurchasesDiscount)

   if (priceAfterDiscounts === 0) priceAfterDiscounts = cart.priceAfterDiscounts
	// cart.allAppliedDiscounts.forEach((discount) => {
	// 	priceAfterDiscounts *= findDiscountFactor(discount)
	// })
//priceAfterDiscounts = cart.priceAfterDiscounts
	return { priceBeforeDiscounts, priceAfterDiscounts }
}
