<?php
// TemplatingTest.php
// Created: 2024-08-04
// Updated: 2025-01-18

declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use Index\{Index,XString};
use Index\Templating\{TplContext,TplEnvironment};
use Index\Templating\Cache\TplFilesystemCache;
use Index\Templating\Extension\TplIndexExtension;
use Index\Templating\Loader\TplFilesystemLoader;
use Twig\Environment as TwigEnvironment;

#[CoversClass(TplContext::class)]
#[CoversClass(TplEnvironment::class)]
#[CoversClass(TplFilesystemCache::class)]
#[CoversClass(TplIndexExtension::class)]
#[CoversClass(TplFilesystemLoader::class)]
final class TemplatingTest extends TestCase {
    public function testEverything(): void {
        $env = new TplEnvironment(
            __DIR__,
            ['IndexTplTest', XString::random(8)]
        );

        $this->assertFalse($env->debug);

        $env->addGlobal('global_var', 'global var value');
        $env->addGlobal('expect', [
            'ndx_version' => Index::version(),
            'twig_version' => TwigEnvironment::VERSION,
        ]);

        $env->addFilter('test_filter', fn(string $text) => ('filter:' . $text));
        $env->addFunction('test_function', fn(string $text) => ('func:' . $text));
        $env->addTest('test_test', fn(string $text) => $text === 'test');

        $rendered = $env->render('TemplatingTest-rendered', [
            'local_var' => 'this var is local',
        ]);

        $this->assertEquals(file_get_contents(__DIR__ . '/TemplatingTest-rendered.html'), $rendered);

        $ctx = $env->load('TemplatingTest-loaded', [
            'context_var' => 'this var is context',
            'variant' => 'toString()',
        ]);

        $ctx->setVar('simple_set', 'simple set call');
        $ctx->setVar('another.context.var.deep', 'applied with fuckery');

        $ctx->setVars([
            'context_var2' => 'applied without fuckery',
        ]);

        $loaded = $ctx->render([
            'local_var' => 'this var is local',
            'variant' => 'render()',
        ]);

        $this->assertEquals(file_get_contents(__DIR__ . '/TemplatingTest-loaded-render.html'), $loaded);
        $this->assertEquals(file_get_contents(__DIR__ . '/TemplatingTest-loaded-string.html'), (string)$ctx);
    }
}