<?php

declare(strict_types=1);

namespace External\FlexiBeeBundle\Synchronizers;

use AbraFlexi\Cenik;
use Query\Operator;

class PriceSynchronizer extends BaseSynchronizer
{
    protected static string $type = 'price';
    protected static ?string $evidenceClass = Cenik::class;

    protected function process(?int $lastSyncTime = null): void
    {
        parent::process($lastSyncTime);

        $this->updateProductsPriceByVariations();
    }

    protected function getItems(?int $lastSyncTime = null): iterable
    {
        if ($this->mode === self::MODE_NORMAL) {
            return parent::getItems($lastSyncTime);
        }

        if ($this->mode === self::MODE_FULL) {
            return $this->flexiBeeApi->getPrices();
        }

        return [];
    }

    public function syncSingleItem(int $id, ?int $flexiId = null): void
    {
        if ($flexiId = $this->flexiBeeUtil->getFlexiId(ProductSynchronizer::getType(), $id)) {
            $items = $this->preprocessChangedItems([$this->flexiBeeApi->getProductPrices($flexiId)]);
            $this->processItem(reset($items));
        }
    }

    protected function processItem(array $item): void
    {
        if (!($mapping = $this->flexiBeeUtil->getItemMapping($item['id']))) {
            return;
        }

        [$productId, $variationId] = $mapping;

        if ($variationId) {
            sqlQueryBuilder()
                ->update('products_variations')
                ->directValues(['price' => $item['cenaZaklBezDph']])
                ->where(Operator::equals(['id' => $variationId]))
                ->execute();
        } else {
            sqlQueryBuilder()
                ->update('products')
                ->directValues(['price' => $item['cenaZaklBezDph']])
                ->where(Operator::equals(['id' => $productId]))
                ->execute();
        }
    }

    private function updateProductsPriceByVariations(): void
    {
        sqlQuery('UPDATE products p
                    JOIN products_variations pv on p.id = pv.id_product
                    SET p.price = (
                            SELECT COALESCE(MIN(IF(pv2.price=0, null, pv2.price)), p.price)
                            FROM products_variations pv2
                            WHERE pv2.id_product = p.id
                        );');
    }
}
