<?php

namespace App\Support;

use Illuminate\Support\Str;

class MediaUrl
{
    public static function fromStoragePath(?string $path): ?string
    {
        if (!$path) {
            return null;
        }

        if (self::isDirectUrl($path)) {
            return $path;
        }

        if (Str::startsWith($path, '/')) {
            return url($path);
        }

        $normalized = self::normalize($path);

        if ($normalized === '') {
            return null;
        }

        return url('media/' . self::encodePath($normalized));
    }

    public static function normalize(string $path): string
    {
        $normalized = str_replace('\\', '/', $path);
        $normalized = preg_replace('~/+~', '/', $normalized) ?? $normalized;

        return ltrim($normalized, '/');
    }

    private static function encodePath(string $path): string
    {
        $segments = array_filter(
            explode('/', self::normalize($path)),
            static fn (string $segment): bool => $segment !== ''
        );

        return implode('/', array_map('rawurlencode', $segments));
    }

    public static function isExternal(?string $path): bool
    {
        return $path !== null && Str::startsWith($path, ['http://', 'https://', '//', 'data:']);
    }

    private static function isDirectUrl(string $path): bool
    {
        return self::isExternal($path);
    }
}
