<?php

namespace KupShop\ArticlesBundle\Twig\DataProvider;

use KupShop\CatalogBundle\Entity\ArticleAuthor;
use KupShop\CatalogBundle\Entity\Wrapper\ArticleAuthorWrapper;
use KupShop\I18nBundle\Translations\ArticlesAuthorsTranslation;
use KupShop\KupShopBundle\Util\Entity\EntityUtil;
use PHPUnit\Runner\Exception;
use Query\Operator;
use Query\Translation;

class ArticleAuthorDataProvider
{
    protected ?ArticleAuthorWrapper $author = null;

    public function __construct(
        private readonly ArticleAuthorWrapper $articleAuthorWrapper,
        private readonly EntityUtil $entityUtil,
    ) {
    }

    public function setAuthor(int $idAuthor): void
    {
        if (empty($idAuthor)) {
            throw new Exception('ID author is null.');
        }

        $rawAuthorData = sqlQueryBuilder()
            ->select('au.id, au.id_block, au.name, au.surname, au.nick, au.note, au.photo')
            ->from('articles_authors', 'au')
            ->andWhere(Operator::equals(['au.id' => $idAuthor]))
            ->andWhere(Translation::coalesceTranslatedFields(ArticlesAuthorsTranslation::class))
            ->execute()
            ->fetchAssociative();

        $author = $this->entityUtil->createEntity($rawAuthorData, ArticleAuthor::class);
        $this->author = (clone $this->articleAuthorWrapper)->setObject($author);
    }

    public function getAuthor(): ?ArticleAuthorWrapper
    {
        return $this->author ?? null;
    }
}
