<?php

namespace App\Tests\Twig;

use App\Twig\ViteAssetExtension;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;

class ViteAssetExtensionTest extends TestCase
{
    public function testAssetDev(): void
    {
        $_ENV['VITE_LOAD'] = "0";

        $cache = $this->createStub(CacheItemPoolInterface::class);

        $extension = new class('/path/to/manifest.json', $cache, null) extends ViteAssetExtension {
            protected function getNonce(): string {
                return 'nonce123';
            }
        };

        $html = $extension->asset('app.js');
        $this->assertStringContainsString('http://localhost:5173', $html);
        $this->assertStringContainsString('nonce="nonce123"', $html);
    }

    public function testAssetProd(): void
    {
        $_ENV['VITE_LOAD'] = "1";

        $cache = $this->createStub(CacheItemPoolInterface::class);
        $item = $this->createStub(CacheItemInterface::class);
        $item->method('isHit')->willReturn(false);
        $item->method('set')->willReturn($item);
        
        $cache->method('getItem')->willReturn($item);

        $manifestPath = sys_get_temp_dir() . '/manifest.json';
        file_put_contents($manifestPath, json_encode([
            'app.js' => ['file' => 'app.123.js', 'css' => ['app.123.css']]
        ]));

        $extension = new class($manifestPath, $cache, null) extends ViteAssetExtension {
            protected function getNonce(): string {
                return 'nonce123';
            }
        };

        $html = $extension->asset('app.js');
        $this->assertStringContainsString('/build/app.123.js', $html);
        $this->assertStringContainsString('/build/app.123.css', $html);
        
        unlink($manifestPath);
    }
}