<?php

declare(strict_types=1);

namespace External\FlexiBeeBundle\Synchronizers;

use Query\Operator;

class StoreSynchronizer extends BaseSynchronizer
{
    protected static string $type = 'store';

    protected function processItem(array $item): void
    {
        if (!($storeId = $this->flexiBeeUtil->getMapping(static::getType(), $item['id']))) {
            $storeId = $this->createStore($item['id'], $this->getStoreName($item));
        }

        sqlQueryBuilder()
            ->update('stores')
            ->directValues(
                [
                    'name' => $this->getStoreName($item),
                ]
            )
            ->where(Operator::equals(['id' => $storeId]))
            ->execute();
    }

    protected function createStore(int $flexiId, string $name): int
    {
        return sqlGetConnection()->transactional(function () use ($flexiId, $name) {
            sqlQueryBuilder()
                ->insert('stores')
                ->directValues(
                    [
                        'name' => $name,
                    ]
                )
                ->execute();

            $storeId = (int) sqlInsertId();

            $this->flexiBeeUtil->createMapping(static::getType(), $flexiId, $storeId);

            return $storeId;
        });
    }

    protected function getStoreName(array $item): string
    {
        return '[FlexiBee] '.$item['nazev'];
    }

    protected function getItems(?int $lastSyncTime = null): iterable
    {
        return $this->flexiBeeApi->getStores();
    }
}
