<?php declare(strict_types=1);
namespace Newland\Toubiz\Sync\Neos\Command\Task;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Newland\Toubiz\Sync\Neos\Command\Helper\ConfigurationHelper;

trait HandlesClientsForArticles
{
    /**
     * @var \Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository
     * @Flow\Inject()
     */
    protected $articleRepository;

    public function setDefaultClient(ConfigurationHelper $configurationHelper, string $where): ClientUpdateResult
    {
        try {
            $defaultClient = $configurationHelper->getDefaultClient(static::$serviceName);
        } catch (InvalidConfigurationException $e) {
            return new ClientUpdateResult(0, 'NULL');
        }

        return $this->articleRepository->withoutLanguageHandling(
            function () use ($defaultClient, $where) {
                $rowsUpdated = $this->articleRepository
                    ->createQueryBuilder('article')
                    ->update()
                    ->set('article.client', ':defaultClient')
                    ->setParameter('defaultClient', $defaultClient)
                    ->where($where)
                    ->andWhere('article.client LIKE \'\' OR article.client LIKE \'default\' OR article.client IS NULL')
                    ->getQuery()
                    ->execute();

                return new ClientUpdateResult($rowsUpdated, $defaultClient);
            }
        );
    }

    public function isConfigured(ConfigurationHelper $configurationHelper): bool
    {
        return $configurationHelper->getConfigurationForService(static::$serviceName) !== null;
    }
}
