<?php

namespace Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\Vat;

use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderDetailTaxRepository;
use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderInvoiceTaxRepository;

/**
 * @implements VatExporterInterface<\OrderInvoice>
 */
class OrderInvoiceVatExporter implements VatExporterInterface
{
    protected OrderDetailTaxRepository $orderDetailTaxRepository;

    protected OrderInvoiceTaxRepository $orderInvoiceTaxRepository;

    public function __construct(
        OrderDetailTaxRepository $orderDetailTaxRepository,
        OrderInvoiceTaxRepository $orderInvoiceTaxRepository
    ) {
        $this->orderDetailTaxRepository = $orderDetailTaxRepository;
        $this->orderInvoiceTaxRepository = $orderInvoiceTaxRepository;
    }

    /**
     * @return array<numeric-string, float>
     */
    public function getVatValuesShipping(\OrderInvoice $orderInvoice): array
    {
        // Get Order Invoice Tax
        return \array_reduce(
            $this->orderInvoiceTaxRepository->getByOrderInvoice($orderInvoice),
            function (array $carry, array $row) {
                if ($row['type'] === 'shipping') {
                    $rate = \number_format($row['rate'], 3, '.', '');

                    $carry[$rate] = ($carry[$rate] ?? 0.0) + $row['amount'];
                }

                return $carry;
            },
            []
        );
    }

    /**
     * @return array<numeric-string, float>
     */
    public function getVatValuesProducts(\Order $order): array
    {
        return \array_reduce(
            $this->orderDetailTaxRepository->getByOrder($order),
            function (array $carry, array $row) {
                $rate = \number_format($row['rate'], 3, '.', '');

                $carry[$rate] = ($carry[$rate] ?? 0.0) + $row['amount'];

                return $carry;
            },
            []
        );
    }

    public function getVatValues(object $document, \Order $order): array
    {
        $ret = $this->getVatValuesShipping($document);

        foreach ($this->getVatValuesProducts($order) as $rate => $amount) {
            $ret[$rate] = ($ret[$rate] ?? 0.0) + $amount;
        }

        return $ret;
    }
}
