<?php

declare(strict_types=1);

namespace App\Support;

final class CdnAssetHelper
{
    private static ?array $manifest = null;

    private static function load(): array
    {
        if (self::$manifest === null) {
            $path = BASE_PATH . '/resources/cdn-manifest.json';
            $raw = @file_get_contents($path);
            if ($raw === false) {
                self::$manifest = ['assets' => []];
            } else {
                $decoded = json_decode($raw, true);
                self::$manifest = is_array($decoded) ? $decoded : ['assets' => []];
            }
        }
        return self::$manifest;
    }

    public static function url(string $logicalName): string
    {
        $base = (string) config('cdn.base');
        $manifest = self::load();
        $path = $manifest['assets'][$logicalName] ?? null;
        if ($path === null) {
            return $base . '/missing/' . ltrim($logicalName, '/');
        }
        return $base . '/' . ltrim($path, '/');
    }

    public static function base(): string
    {
        return (string) config('cdn.base');
    }

    public static function manifestForJs(): array
    {
        return self::load()['assets'] ?? [];
    }
}
