<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Blog\Support\PluginManager;
use App\Models\Comment;
use App\Models\Post;
use App\Models\Setting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Plugins\Demo\HelloWorld\ServiceProvider;
use Tests\TestCase;

class DemoPluginTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        // demo 插件默认未启用（不在 config/plugins.php enabled），测试中手动 boot 验证其代码
        ServiceProvider::bootPlugin(app(PluginManager::class));
    }

    private function makePost(): Post
    {
        return Post::create([
            'title' => '演示',
            'slug' => 'demo-'.uniqid(),
            'content' => '内容',
            'content_format' => 'markdown',
            'status' => 'published',
            'published_at' => now(),
        ]);
    }

    public function test_hello_shortcode_filter_renders_greeting(): void
    {
        Setting::set('hello_world_greeting', '嗨');

        $html = app(PluginManager::class)->applyFilters('post.rendered', '正文 [hello 世界]', $this->makePost());

        $this->assertStringContainsString('嗨，世界！', $html);
        $this->assertStringNotContainsString('[hello', $html);
    }

    public function test_comment_created_action_writes_log(): void
    {
        $post = $this->makePost();
        $comment = Comment::create([
            'post_id' => $post->id,
            'author_name' => '游客',
            'content' => '演示评论内容',
            'status' => 'pending',
        ]);

        app(PluginManager::class)->doAction('comment.created', $comment);

        $this->assertDatabaseHas('hello_world_logs', ['comment_id' => $comment->id]);
    }

    public function test_hello_world_route_renders_plugin_view(): void
    {
        $this->get('/hello-world')
            ->assertOk()
            ->assertSee('Hello World 演示页');
    }
}
