<?php

namespace App\Support;

use Illuminate\Support\Facades\Storage;

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

        if (preg_match('/^https?:\/\//', $path) === 1) {
            return $path;
        }

        if (file_exists(public_path($path))) {
            return asset($path);
        }

        try {
            if (! Storage::disk('public')->exists($path)) {
                return null;
            }

            return route('public.media', ['path' => ltrim($path, '/')]);
        } catch (\Throwable) {
            return null;
        }
    }
}
