<?php

/**
 * 文件功能：房间名称安全校验测试
 * 验证建房与改房时会拦截可能注入前端的危险名称。
 */

namespace Tests\Feature;

use App\Models\Room;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * 房间名称安全校验测试
 * 负责回归房间名称中的尖括号会被后端验证直接拦截。
 */
class RoomRequestSecurityTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 测试建房时不能提交包含尖括号的危险房间名称。
     */
    public function test_cannot_create_room_with_html_like_name(): void
    {
        $user = User::factory()->create(['user_level' => 10]);

        $response = $this->actingAs($user)->post(route('rooms.store'), [
            'name' => '<img src=x onerror=alert(1)>',
            'description' => '危险名称测试',
        ]);

        $response->assertSessionHasErrors('name');
        $this->assertDatabaseMissing('rooms', [
            'room_name' => '<img src=x onerror=alert(1)>',
        ]);
    }

    /**
     * 测试修改房间时同样不能把危险名称写入数据库。
     */
    public function test_cannot_update_room_with_html_like_name(): void
    {
        $owner = User::factory()->create();
        $room = Room::create([
            'room_name' => '安全房间',
            'room_owner' => $owner->username,
            'room_keep' => false,
        ]);

        $response = $this->actingAs($owner)->from(route('rooms.index'))->put(route('rooms.update', $room->id), [
            'name' => '<svg onload=alert(1)>',
            'description' => '危险更新测试',
        ]);

        $response->assertSessionHasErrors('name');
        $this->assertDatabaseHas('rooms', [
            'id' => $room->id,
            'room_name' => '安全房间',
        ]);
    }
}
