<?php

namespace KupShop\ComponentsBundle\Twig\Components\Account\OrderDetail;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\OrderDataTrait;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Price\Price;
use KupShop\OrderingBundle\Util\Order\OrderInfo;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Account/OrderDetail/Discounts/Discounts.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Discounts extends BaseComponent
{
    use OrderDataTrait;

    protected array $discounts;
    protected Price $totalDiscounts;

    public function __construct(
        private readonly OrderInfo $orderInfo,
    ) {
    }

    public function getDiscounts(): array
    {
        $order = $this->order->getObject();
        if (!($order instanceof \Order)) {
            return [];
        }

        if (!isset($this->discounts)) {
            $this->discounts = $this->orderInfo->getDiscounts($order);

            $currency = Contexts::get(CurrencyContext::class)->getOrDefault($this->order->getCurrency());
            $total = \DecimalConstants::zero();
            array_walk($this->discounts, function (array &$discount) use (&$total, $currency): void {
                $total = $total->add($discount['totalPrice']);
                $discount['totalPrice'] = new Price($discount['totalPrice'], $currency, 0);
            });
            $this->totalDiscounts = new Price($total, $currency, 0);
        }

        return $this->discounts;
    }

    public function getTotalDiscounts(): Price
    {
        if (!isset($this->totalDiscounts)) {
            $this->getDiscounts();
        }

        return $this->totalDiscounts;
    }
}
