<?php

namespace AutoAdmin\Bundle\Content\Service;

use AutoAdmin\Bundle\BrickBuilder\Attributes\BrickBuilder;
use AutoAdmin\Bundle\BrickBuilder\Service\BrickService;
use AutoAdmin\Bundle\Content\Model\BrickInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use ReflectionClass;

class ContentService
{
    public function __construct(
        protected BrickService $brickService,
    ) {
    }

    public function hasBrickTypeOf(object $content, string $type): bool
    {
        if ($this->hasBrickTypeInAttributes($content, $type)) {
            return true;
        }

        $brick = null;

        if ($content instanceof BrickInterface) {
            $brick = $content->getBrick();
        } elseif ($content instanceof TranslatableInterface) {
            $translation = $content->getCurrentTranslation();
            if ($translation instanceof BrickInterface) {
                $brick = $translation->getBrick();
            }
        }

        return $this->brickService->isOrHasChildOfType($brick, $type);
    }

    private function hasBrickTypeInAttributes(object $content, string $type): bool
    {
        $reflectionClass = new ReflectionClass($content);

        foreach ($reflectionClass->getProperties() as $property) {
            $attributes = $property->getAttributes(BrickBuilder::class);

            if (!empty($attributes)) {
                /** @var BrickBuilder $brickAttribute */
                $brickAttribute = $attributes[0]->newInstance();

                if ($brickAttribute->getType() === $type) {
                    return true;
                }
            }
        }

        return false;
    }
}
