<?php

declare(strict_types=1);

namespace Ost\ReimportDataengine\Service;

final class FeedValueResolver
{
    /**
     * @param array<int|string, string>|null $breadcrumb
     */
    public function resolveBreadcrumb(?array $breadcrumb): string
    {
        if (!is_array($breadcrumb) || $breadcrumb === []) {
            return '';
        }

        $parts = array_values(array_slice($breadcrumb, 2));
        $parts = array_filter($parts, static fn (mixed $part): bool => is_string($part) && $part !== '');

        return implode(' > ', $parts);
    }

    public function stringifyScalar(mixed $value): string
    {
        if (is_scalar($value)) {
            return (string) $value;
        }

        return '';
    }

    public function toAbsoluteUrl(string $path, string $baseUrl, string $scheme = 'https'): string
    {
        if ($path === '') {
            return '';
        }

        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            return $path;
        }

        if (str_starts_with($path, '//')) {
            return $scheme . ':' . $path;
        }

        $normalizedPath = '/' . ltrim($path, '/');

        if ($baseUrl === '') {
            return $normalizedPath;
        }

        return rtrim($baseUrl, '/') . $normalizedPath;
    }
}
