<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiShared\Types\Content;

use KupShop\ContentBundle\Util\Block;
use KupShop\GraphQLBundle\ApiShared\ApiUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

#[Type]
class EditableContent
{
    public function __construct(
        private ?int $id,
        private array $blocks,
        private ?string $objectType = null,
        private ?int $objectId = null,
    ) {
    }

    #[Field(description: 'ID editovatelné obsahu.')]
    public function getId(): int
    {
        // pokud jeste neexistuje root block, tak ho vytvorim, aby existoval vzdy, kdyz si reknu o jeho ID
        if (!$this->id && $this->objectType && $this->objectId) {
            static $block;

            if (!$block) {
                $block = ServiceContainer::getService(Block::class);
            }

            return $block->getRootBlockId($this->objectType, $this->objectId);
        }

        return $this->id;
    }

    /**
     * @return EditableArea[]
     */
    #[Field(description: 'Oblasti obsahující popisek a jeho data.')]
    public function getAreas(): array
    {
        return ApiUtil::wrapItems(
            $this->blocks,
            EditableArea::class
        );
    }
}
