<?php

namespace Tests\Feature;

use App\Models\Category;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Tags\Tag;
use Tests\TestCase;

/**
 * 中文内容端到端回归：中文标签/分类/文章 slug 必须可访问。
 * （此前路由约束 [A-Za-z0-9-]+ 导致 /tags/随笔.shtml 404 且测试未覆盖）
 */
class ChineseContentTest extends TestCase
{
    use RefreshDatabase;

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

        $this->seed();

        $user = User::create(['name' => '作者', 'email' => 'cn@test.com', 'password' => bcrypt('x')]);

        // 中文分类
        $category = Category::create(['name' => '生活随笔', 'slug' => 'shenghuo-suibi']);

        // 中文标题文章（slug 为空时回退 id）
        Post::create([
            'user_id' => $user->id,
            'category_id' => $category->id,
            'title' => '第一篇中文文章',
            'slug' => null,
            'content' => '中文内容',
            'content_format' => 'markdown',
            'status' => 'published',
            'published_at' => now(),
        ]);

        // 中文标签（spatie 中文 slug 为空，链接回退标签名）
        Tag::create(['name' => '随笔', 'type' => 'post']);
    }

    public function test_chinese_tag_page_is_accessible(): void
    {
        $tag = Tag::findFromString('随笔', 'post');
        $post = Post::first();
        $post->attachTag($tag);

        $this->get('/tags/'.rawurlencode('随笔').'.shtml')->assertOk()->assertSee('第一篇中文文章');
        // 无后缀版本 301 到 .shtml
        $this->get('/tags/'.rawurlencode('随笔'))->assertRedirect('/tags/%E9%9A%8F%E7%AC%94.shtml');
    }

    public function test_chinese_tag_from_sidebar_link(): void
    {
        $tag = Tag::findFromString('随笔', 'post');
        $post = Post::first();
        $post->attachTag($tag);

        // 首页侧边栏/文章页生成的链接应可访问
        $this->get('/')->assertOk()->assertSee('/tags/%E9%9A%8F%E7%AC%94.shtml');
        $this->get('/posts/'.$post->id.'.shtml')->assertOk()->assertSee('/tags/%E9%9A%8F%E7%AC%94.shtml');
    }

    public function test_post_without_slug_uses_id(): void
    {
        $post = Post::first();
        $this->assertNull($post->slug);

        $this->get('/posts/'.$post->id.'.shtml')->assertOk()->assertSee('第一篇中文文章');
        $this->get('/posts/'.$post->id)->assertRedirect('/posts/'.$post->id.'.shtml');
    }

    public function test_category_slug_route(): void
    {
        $this->get('/category/shenghuo-suibi.shtml')->assertOk()->assertSee('第一篇中文文章');
    }
}
