<?php

namespace Mtc\Plugins\BlockManager\Tests\Feature;

use Illuminate\Support\Str;
use Mtc\Modules\BlockRegistry\Models\BlockRegistry;
use Mtc\Plugins\BlockManager\Models\BlockManagerBlock;
use Mtc\Plugins\BlockManager\Services\BlockShipService;
use Tests\TestCase;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

/**
 * End-to-end render check: ship a composed block, then ask the real Twig
 * instance to render it. This is the regression net for the loader-path bug
 * that made every BlockManager-shipped block unrenderable (variant partials
 * lived at plugins/BlockManager/elements/ which Twig wasn't told about).
 *
 * If this test goes red, the symptom in the admin UI is the cryptic
 * "Failed to render block preview" overlay.
 */
class ShipRenderIntegrationTest extends TestCase
{
    /** @var string[] */
    private array $createdUuids = [];

    /** @var string[] */
    private array $shippedSlugs = [];

    protected function tearDown(): void
    {
        $twigDir = base_path('sites/default/templates/includes/page_blocks');
        $jsonDir = base_path('modules/BlockRegistry/blocks');

        foreach ($this->shippedSlugs as $slug) {
            @unlink($twigDir . "/{$slug}.twig");
            @unlink($jsonDir . "/{$slug}.json");
            BlockRegistry::where('slug', $slug)->delete();
        }

        if (!empty($this->createdUuids)) {
            BlockManagerBlock::whereIn('uuid', $this->createdUuids)->delete();
        }

        parent::tearDown();
    }

    public function test_shipped_block_renders_via_twig_without_loader_error(): void
    {
        $block = $this->seedShipableBlock();
        app(BlockShipService::class)->ship($block);
        $this->shippedSlugs[] = $block->slug;

        // The shipped Twig lives at includes/page_blocks/{slug}.twig and
        // includes element variant partials by their short paths
        // (e.g. "heading/variants/default.twig"). Those paths must resolve
        // against the catalogue loader root that BlockManagerServiceProvider::boot()
        // registers. Build a minimal Twig env here mirroring those two roots
        // — app('twig') isn't carried across the per-test container reset.
        $loader = new FilesystemLoader([
            base_path('sites/default/templates'),
            base_path('plugins/BlockManager/elements'),
        ]);
        $twig = new Environment($loader, ['cache' => false]);

        $html = $twig->render("includes/page_blocks/{$block->slug}.twig", [
            'fields' => [
                'heading_text'   => 'Render Smoke',
                'heading_level'  => 'h2',
                'button_label'   => 'Click me',
                'button_link'    => '#',
                'button_target'  => '_self',
            ],
        ]);

        $this->assertIsString($html);
        $this->assertStringContainsString(
            'bm-heading--default',
            $html,
            "Rendered output must include the heading default variant's BEM class — the include path resolved correctly."
        );
        $this->assertStringContainsString(
            'bm-button--primary',
            $html,
            "Rendered output must include the button primary variant's BEM class — the include path resolved correctly."
        );
        $this->assertStringContainsString(
            'Render Smoke',
            $html,
            "Field values must thread through the include bindings."
        );
    }

    private function seedShipableBlock(): BlockManagerBlock
    {
        $uuid = (string) Str::uuid();
        $this->createdUuids[] = $uuid;

        return BlockManagerBlock::create([
            'uuid'           => $uuid,
            'slug'           => 'phase-ship-render-' . Str::random(8),
            'name'           => 'Ship Render Probe',
            'description'    => 'Auto-seeded by ShipRenderIntegrationTest.',
            'icon'           => 'fa-cube',
            'structure_json' => [
                'elements' => [
                    [
                        'instance_id'  => 'el-001',
                        'element_type' => 'heading',
                        'variant'      => 'default',
                        'field_name'   => 'heading',
                    ],
                    [
                        'instance_id'  => 'el-002',
                        'element_type' => 'button',
                        'variant'      => 'primary',
                        'field_name'   => 'button',
                    ],
                ],
            ],
        ]);
    }
}
