<?php

namespace Tests\Feature;

use App\Models\Setting;
use App\Models\Post;
use App\Models\Category;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ThemeTest extends TestCase
{
    use RefreshDatabase;

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

        $this->seed();

        $user = User::create(['name' => '作者', 'email' => 't@test.com', 'password' => bcrypt('x')]);
        $category = Category::create(['name' => '分类', 'slug' => 'cat']);
        Post::create([
            'user_id' => $user->id,
            'category_id' => $category->id,
            'title' => '主题测试',
            'slug' => 'theme-test',
            'content' => '内容',
            'content_format' => 'markdown',
            'status' => 'published',
            'published_at' => now(),
        ]);
    }

    public function test_sablog_theme_renders_classic_layout(): void
    {
        app(\App\Blog\Support\ThemeManager::class)->activate('sablog');
        $this->get('/')->assertOk()->assertSee('outmain');
        $this->get('/posts/theme-test.shtml')->assertOk()->assertSee('outmain');
    }

    public function test_modern_theme_renders_modern_layout(): void
    {
        app(\App\Blog\Support\ThemeManager::class)->activate('modern');
        $this->get('/')->assertOk()->assertSee('m-header');
        $this->get('/posts/theme-test.shtml')->assertOk()->assertSee('m-header');
    }

    public function test_theme_assets_are_served(): void
    {
        $this->get('/themes/sablog/assets/style.css')->assertOk()->assertHeader('Content-Type', 'text/css; charset=utf-8');
        $this->get('/themes/modern/assets/style.css')->assertOk();
        $this->get('/themes/nonexistent/assets/style.css')->assertNotFound();
    }

    public function test_unknown_theme_falls_back_to_default(): void
    {
        Setting::set('active_theme', 'does-not-exist');
        $this->get('/')->assertOk();
    }

    public function test_demo_theme_renders(): void
    {
        app(\App\Blog\Support\ThemeManager::class)->activate('demo');
        $this->get('/')->assertOk()->assertSee('Demo 主题');
    }

    public function test_theme_asset_url_respects_explicit_theme(): void
    {
        // 回归：theme('asset', path, name) 必须用指定主题，而不是激活主题（否则主题管理页所有卡片显示同一张图）
        $this->assertStringContainsString('/themes/sablog/assets/screenshot.png', theme('asset', 'screenshot.png', 'sablog'));
        $this->assertStringContainsString('/themes/modern/assets/screenshot.png', theme('asset', 'screenshot.png', 'modern'));
    }
}
