<?php

namespace AutoAdmin\Bundle\Seo\Schema\Builder;

use AutoAdmin\Bundle\Content\Breadcrumbs\BreadcrumbsService;
use AutoAdmin\Bundle\Content\Context\ContentContext;
use AutoAdmin\Bundle\Seo\Schema\Model\SchemaStack;
use Spatie\SchemaOrg\Schema;

class BreadcrumbsSchemaBuilder implements SchemaBuilderInterface
{
    public function __construct(
        protected ContentContext $contentContext,
        protected BreadcrumbsService $breadcrumbsService
    ) {
    }

    public function build(SchemaStack $schema)
    {
        if ($items = $this->breadcrumbsService->compile()) {
            $bc = Schema::breadcrumbList();
            $bcItems = [];
            foreach ($items as $idx => $item) {
                $bcItems[] = Schema::listItem()
                    ->position($idx + 1)
                    ->name($item['label'])
                    ->item($item['url']);
            }
            $bc->itemListElement($bcItems);

            if (!$schema->hasType($bc)) {
                $schema->add($bc);
            }
        }
    }
}
