<?php

namespace AutoAdmin\Bundle\Seo\Schema\Builder;

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

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

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

                $this->prependDomain($item, $bcItem);

                $bcItems[] = $bcItem;
            }
            $bc->itemListElement($bcItems);

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

    protected function prependDomain($item, $bcItem): void
    {
        if (!empty($item['url']) && !str_starts_with($item['url'], 'http://') && !str_starts_with($item['url'], 'https://')) {
            $bcItem->item('https://' . $this->siteContextHelper->getCurrentContext()->getDomain()->getDomain() . $item['url']);
        }
    }
}
