<?php

declare(strict_types=1);

namespace Myvetshop\Module\Clinique\Api\Insight\Serializer;

use Myvetshop\Module\Clinique\Generated\Jane\Insight\Model\OrdersGetResponse200Item;
use Myvetshop\Module\Clinique\Generated\Jane\Insight\Normalizer\OrdersGetResponse200ItemDiscountsItemNormalizer;
use Myvetshop\Module\Clinique\Generated\Jane\Insight\Normalizer\OrdersGetResponse200ItemNormalizer;
use Myvetshop\Module\Clinique\Generated\Jane\Insight\Normalizer\OrdersGetResponse200ItemPaymentsItemNormalizer;
use Myvetshop\Module\Clinique\Generated\Jane\Insight\Normalizer\OrdersGetResponse200ItemProductsItemNormalizer;
use Myvetshop\Module\Clinique\Generated\Jane\Insight\Normalizer\OrdersGetResponse200ItemRefundsItemNormalizer;

/**
 * @extends AbstractInsightSerializer<OrdersGetResponse200Item>
 */
class InsightOrderSerializer extends AbstractInsightSerializer
{
    public static function getNormalizers(): array
    {
        return [
            new OrdersGetResponse200ItemNormalizer(),
            new OrdersGetResponse200ItemProductsItemNormalizer(),
            new OrdersGetResponse200ItemDiscountsItemNormalizer(),
            new OrdersGetResponse200ItemRefundsItemNormalizer(),
            new OrdersGetResponse200ItemPaymentsItemNormalizer(),
        ];
    }

    public static function getModelClass(): string
    {
        return OrdersGetResponse200Item::class;
    }

    /**
     * @param list<array<string, string>> $orders
     * @param array{
     *     products: list<array<string, string>>,
     *     discounts: list<array<string, string>>,
     *     refunds: list<array<string, string>>,
     *     payments: list<array<string, string>>,
     * } $orderElements
     *
     * @return list<array<string, string|list<array<string, string>>>>
     */
    public static function prepareOrdersArray(array $orders, array $orderElements): array
    {
        foreach ($orderElements as $name => $elements) {
            $orderElements[$name] = \array_reduce($elements, function (array $carry, array $element) {
                // Suppression de l'id de commande inutile
                $orderId = $element['order_id'];
                unset($element['order_id']);

                // Création de la liste des éléments pour la commande concernée si elle n'existe pas
                \array_key_exists($orderId, $carry) ?: $carry[$orderId] = [];

                // Ajout de l'élément à la liste
                $carry[$orderId][] = $element;

                return $carry;
            }, []);
        }

        return \array_map(function ($order) use ($orderElements) {
            // Ajout des éléments
            foreach ($orderElements as $name => $elements) {
                $order[$name] = \array_key_exists($order['id'], $elements) ? $elements[$order['id']] : [];
            }

            return $order;
        }, $orders);
    }
}
