<?php

namespace AutoAdmin\Bundle\Content\Duplicator;

use AutoAdmin\Bundle\BrickBuilder\Attributes\BrickBuilder;
use AutoAdmin\Bundle\BrickBuilder\Brick\BrickHandlerManagerInterface;
use AutoAdmin\Bundle\BrickBuilder\Storage\ObjectSettingFormat;

class BrickOwnerContentDuplicator extends AbstractDuplicator
{
    public function __construct(
        protected BrickHandlerManagerInterface $handlerManager,
        protected ObjectSettingFormat $brickFormat,
    ) {
    }

    public function supportAttributes(): array
    {
        return [
            BrickBuilder::class,
        ];
    }

    public function duplicate(object $entity, object $duplicate): object
    {
        $brickBuilderProps = $this->getPropertiesWithAttribute($entity, BrickBuilder::class);
        /** @var \ReflectionProperty $brickBuilderProp */
        foreach ($brickBuilderProps as $brickBuilderProp) {
            $brick = $brickBuilderProp->getValue($entity);
            if ($brick !== null) {
                $newBrick = $this->duplicatorManager->duplicate($brick);
                $brickBuilderProp->setValue($duplicate, $newBrick);
            }
        }

        return $duplicate;
    }
}
