<?php

declare(strict_types=1);

namespace External\HannahBundle\Util;

use KupShop\KupShopBundle\Util\Database\QueryHint;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use KupShop\OrderingBundle\Util\Order\OrderInfo;

class OrderUtil
{
    public function __construct(
        private Configuration $configuration,
        private OrderInfo $orderInfo,
    ) {
    }

    public function getOrderNumberWithPrefix(\Order $order): string
    {
        if ($prefix = $this->getOrderProcess($order)) {
            return $prefix.'_'.$order->order_no;
        }

        return $order->order_no;
    }

    public function getOrderProcess(\Order $order): ?string
    {
        if ($process = $this->getOrderMarketplaceProcess($order)) {
            return $process;
        }

        // vychozi nastaveni
        $prefix = $this->configuration->getProcessByLanguage($order->getLanguage());
        if (!empty($prefix)) {
            return rtrim($prefix, '_');
        }

        return null;
    }

    public function getOrderMarketplaceProcess(\Order $order): ?string
    {
        // marketplace muze nastavit custom data `sapProcess`, tak pokud to je vyplneny, tak beru z toho
        if ($order->getData('sapProcess')) {
            return $order->getData('sapProcess');
        }

        // pokud nemam dropshipment info, tak vracim `null`
        if (!($dropshipmentInfo = QueryHint::withRouteToMaster(fn () => $this->orderInfo->getOrderDropshipmentInfo($order->id)))) {
            return null;
        }

        // jinak to zkousim dohledat proces podle nastaveni dropshipmentu
        $dropshipment = $dropshipmentInfo['dropshipment'];

        // prefix podle marketplacu
        $prefixByMarketplace = Mapping::mapKeys(
            $dropshipment['data']['sap']['prefix_by_marketplace'] ?? [],
            fn ($k, $v) => [$v['marketplace'], $v['prefix']]
        );
        $marketplace = $dropshipmentInfo['external']['data']['marketplace'] ?? null;

        if (!empty($prefixByMarketplace[$marketplace])) {
            return $prefixByMarketplace[$marketplace];
        }

        // prefix podle zeme doruceni
        $prefixByCountry = $dropshipment['data']['sap_order_prefix_by_country'] ?? [];
        if (!empty($prefixByCountry[$order->delivery_country])) {
            return $prefixByCountry[$order->delivery_country];
        }

        // vychozi prefix od dropshipmentu
        if ($dropshipment['data']['sap_order_prefix'] ?? false) {
            return $dropshipment['data']['sap_order_prefix'];
        }

        return null;
    }
}
