<?php

namespace Tests\Feature;

use App\Filament\Resources\TerminalResource;
use App\Models\Station;
use App\Models\Terminal;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class TerminalPromptFormTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected function setUp(): void
    {
        parent::setUp();
        $this->user = User::factory()->create();
    }

    /** @test */
    public function terminal_can_be_created_with_prompt()
    {
        $this->actingAs($this->user);

        $station = Station::factory()->create();

        $terminalData = [
            'name' => '测试终端',
            'code' => 'TEST-001',
            'ip_address' => '192.168.1.100',
            'station_id' => $station->id,
            'prompt' => [
                'prompt_template' => '你是一个智能助手，当前用户是 {user}。',
            ],
        ];

        Livewire::test(TerminalResource\Pages\CreateTerminal::class)
            ->fillForm($terminalData)
            ->call('create')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas('terminals', [
            'name' => '测试终端',
            'code' => 'TEST-001',
        ]);

        $terminal = Terminal::where('code', 'TEST-001')->first();
        $this->assertNotNull($terminal->prompt);
        $this->assertEquals('你是一个智能助手，当前用户是 {user}。', $terminal->prompt->prompt_template);
    }

    /** @test */
    public function terminal_prompt_can_be_updated()
    {
        $this->actingAs($this->user);

        $terminal = Terminal::factory()->create();
        $terminal->prompt()->create([
            'prompt_template' => '旧的提示词',
            'variables' => [],
        ]);

        $newPromptData = [
            'name' => $terminal->name,
            'code' => $terminal->code,
            'prompt' => [
                'prompt_template' => '新的提示词模板',
            ],
        ];

        Livewire::test(TerminalResource\Pages\EditTerminal::class, ['record' => $terminal->id])
            ->fillForm($newPromptData)
            ->call('save')
            ->assertHasNoFormErrors();

        $terminal->refresh();
        $this->assertEquals('新的提示词模板', $terminal->prompt->prompt_template);
    }

    /** @test */
    public function edit_form_loads_existing_prompt()
    {
        $this->actingAs($this->user);

        $terminal = Terminal::factory()->create();
        $terminal->prompt()->create([
            'prompt_template' => '现有的提示词',
            'variables' => ['user'],
        ]);

        Livewire::test(TerminalResource\Pages\EditTerminal::class, ['record' => $terminal->id])
            ->assertFormSet([
                'prompt.prompt_template' => '现有的提示词',
            ]);
    }
}
