<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Shop;

use CpCreation\VitiCore\Shop\DTO\ShippingContext;
use CpCreation\VitiCore\Shop\DTO\ShippingQuote;
use CpCreation\VitiCore\Shop\Repository\ShippingConfigRepository;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;

#[AsDecorator(decorates: ShippingCalculatorInterface::class, priority: 100)]
final class FreeShippingDecorator implements ShippingCalculatorInterface
{
    public function __construct(
        #[AutowireDecorated]
        private readonly ShippingCalculatorInterface $inner,
        private readonly ShippingConfigRepository $shippingConfigRepository,
    ) {
    }

    public function calculate(ShippingContext $context): ShippingQuote
    {
        $shippingConfig = $this->shippingConfigRepository->findOne();

        if (
            null !== $shippingConfig
            && $shippingConfig->getAmountFreeShipping()
            && $context->itemsTotalTTC >= $shippingConfig->getAmountFreeShipping()
        ) {
            return ShippingQuote::fromTTC(
                amountTTC: 0,
                taxRate: 0.0,
                shippingName: null,
                details: ['free_shipping_threshold'],
            );
        }

        return $this->inner->calculate($context);
    }
}
