<?php

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

use Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\OrderInvoiceLineProviderInterface;
use Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\OrderSlipLineProviderInterface;
use Myvetshop\Module\Clinique\Accounting\Export\Model\SimpleAccountingLine;
use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderDetailTaxRepository;
use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderInvoiceTaxRepository;
use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderSlipDetailRepository;

class VatProvider implements OrderInvoiceLineProviderInterface, OrderSlipLineProviderInterface
{
    /**
     * @var array<numeric-string|string, string>
     */
    public const VAT_ACCOUNT_BY_RATE
        = [
            '5.500' => '4457111',
            '10.000' => '4457113',
            '20.000' => '445711',
        ];

    protected OrderDetailTaxRepository $orderDetailTaxRepository;

    protected OrderInvoiceTaxRepository $orderInvoiceTaxRepository;

    protected OrderSlipDetailRepository $orderSlipDetailRepository;

    /**
     * @param array<numeric-string|string, float> $amountsByRate
     *
     * @return list<SimpleAccountingLine>
     */
    protected function mapAmountsToAccount(array $amountsByRate, bool $asCredit): array
    {
        $ret = [];

        foreach ($amountsByRate as $rate => $amount) {
            if (!isset(self::VAT_ACCOUNT_BY_RATE[$rate])) {
                throw new \Exception('VAT Rate not supported');
            }

            $account = self::VAT_ACCOUNT_BY_RATE[$rate];

            $ret[] = new SimpleAccountingLine(
                $account,
                $asCredit ? $amount : 0.00,
                $asCredit ? 0.00 : $amount,
            );
        }

        return $ret;
    }

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

    public function getInvoiceAccountingLines(\OrderInvoice $orderInvoice, \Order $order): array
    {
        // Get VAT on Products (include VAT reduction by discounts)
        $vatByRate = \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;
            },
            []
        );

        // Get VAT on Shipping
        $shippingVat = \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;
            },
            []
        );

        foreach ($shippingVat as $rate => $amount) {
            $vatByRate[$rate] = ($vatByRate[$rate] ?? 0.0) + $amount;
        }

        return $this->mapAmountsToAccount($vatByRate, true);
    }

    public function getSlipAccountingLines(\OrderSlip $orderSlip, \Order $order): array
    {
        $orderDetailTax = $this->orderDetailTaxRepository->getByOrder($order);

        $vatByRate = \array_reduce(
            $this->orderSlipDetailRepository->getByOrderSlip($orderSlip),
            function (array $carry, array $row) use ($orderDetailTax) {
                $taxDetail = $orderDetailTax[$row['id_order_detail']] ?? null;

                if (!$taxDetail) {
                    throw new \Exception("Can't get order detail tax for OrderDetail#" . $row['id_order_detail']);
                }

                $rate = \number_format($taxDetail['rate'], 3, '.', '');

                $carry[$rate] = ($carry[$rate] ?? 0.0) + ($row['amount_tax_incl'] - $row['amount_tax_excl']);

                return $carry;
            },
            []
        );

        if ($orderSlip->total_shipping_tax_incl != $orderSlip->total_shipping_tax_excl) {
            // TODO : Better handling of shipping VAT Rate
            $vatByRate['20.000'] = ($vatByRate['20.000'] ?? 0) + \round(
                $orderSlip->total_shipping_tax_incl - $orderSlip->total_shipping_tax_excl,
                2
            );
        }

        // TODO : Handle proper tax rate for discount
        if ($orderSlip->order_slip_type == 1) {
            $discountAmount = \round(
                $order->total_discounts_tax_incl - $order->total_discounts_tax_excl,
                2
            );
            if ($discountAmount) {
                if (!isset($vatByRate['20.000']) || \round($vatByRate['20.000'], 2) < $discountAmount) {
                    throw new \Exception('Error with discount VAT computation, aborting. Slip#' . $orderSlip->id);
                }
                $vatByRate['20.000'] -= $discountAmount;
            }
        }

        return $this->mapAmountsToAccount($vatByRate, false);
    }

    /**
     * @param \OrderInvoice|\OrderSlip $document
     */
    public function getAccountingLines($document, \Order $order): array
    {
        return $document instanceof \OrderInvoice
            ? $this->getInvoiceAccountingLines($document, $order)
            : $this->getSlipAccountingLines($document, $order);
    }
}
