<?php

declare(strict_types=1);

namespace App\Support;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Throwable;

/**
 * 为 storage/app/private（local 盘 serve=true）生成可预览/下载的签名 URL。
 *
 * 生产环境 ServeFile 要求签名；Filament 在 temporaryUrl 失败时会回退到无签名 path，导致图片不显示。
 */
final class DberpPrivateStorageServeUrl
{
    public const DISK = 'local';

    public const SERVE_ROUTE = 'storage.local';

    public function forPath(string $path): ?string
    {
        $path = trim($path);

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

        $storage = Storage::disk(self::DISK);

        if (! $storage->exists($path)) {
            return null;
        }

        $expiration = now()->addMinutes(
            max(1, (int) config('filament.temporary_file_url_expiry_minutes', 30)),
        );

        if (Route::has(self::SERVE_ROUTE)) {
            try {
                // local 私有盘由 ServeFile::hasValidRelativeSignature 校验，必须使用相对签名。
                $signedRelativeUrl = URL::temporarySignedRoute(
                    self::SERVE_ROUTE,
                    $expiration,
                    ['path' => $path],
                    absolute: false,
                );

                return URL::to($signedRelativeUrl);
            } catch (Throwable) {
                // 路由不可用时再尝试磁盘适配器自带 temporaryUrl
            }
        }

        if ($storage->providesTemporaryUrls()) {
            try {
                $url = $storage->temporaryUrl($path, $expiration);

                if (is_string($url) && $url !== '') {
                    return $url;
                }
            } catch (Throwable) {
                return null;
            }
        }

        return null;
    }
}
