<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareMobile\Classes\ApiRequestCompatibility;

use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;
use Shopware\Plugins\ViisonCommon\Classes\Util\UuidUtil;
use Shopware\Plugins\ViisonPickwareCommon\Classes\ApiRequestCompatibility\Layer;

class Orders20220216 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2022-02-16';
    }

    /**
     * Ensures our pickware idempotency key header is present on the request.
     *
     * pre PUT /api/orders
     */
    public function preBatchAction()
    {
        $this->ensurePickwareIdempotencyHeaderExists();
    }

    private function ensurePickwareIdempotencyHeaderExists()
    {
        if (!$this->request->getHeader('Pickware-Idempotency-Key')) {
            $idempotencyKey = UuidUtil::generateUuidV4();
            $this->request->setHeader('Pickware-Idempotency-Key', $idempotencyKey);
            // In SW 5.6 the `setHeader()` method does not set the header on the `server` parameter bag of the symfony
            // request but instead uses the `headers` parameter bag with a wrong key, however to add insult to injury
            // the `headers` parameter bag is not even evaluated when using `getHeader()`. Thus, we need to manually set
            // the header on the `server` parameter bag here.
            if (ViisonCommonUtil::assertMinimumShopwareVersion('5.6.0')
                && !ViisonCommonUtil::assertMinimumShopwareVersion('5.7.0')
                && property_exists($this->request, 'server')
            ) {
                $this->request->server->set('HTTP_PICKWARE_IDEMPOTENCY_KEY', $idempotencyKey);
            }
        }
    }
}
