<?php
// tests/Feature/TcpSocketClientTest.php
namespace Tests\Feature;

use Tests\TestCase;
use App\Services\TcpSocketClient;

class TcpSocketClientTest extends TestCase
{
    public function testCanSendAndReceiveTcpMessage()
    {
        $host = '127.0.0.1';
        $port = 12345;

        // 建立一個假的 TCP server (background)
        $pid = pcntl_fork();
        if ($pid == -1) {
            $this->fail("Unable to fork process for mock TCP server.");
        } elseif ($pid == 0) {
            // 子處理序：啟動簡單 TCP server
            $socket = stream_socket_server("tcp://$host:$port", $errno, $errstr);
            if (!$socket) {
                exit(1);
            }
            $conn = stream_socket_accept($socket);
            $data = fread($conn, 1024); // 收資料
            fwrite($conn, "Echo: " . $data); // 回傳資料
            fclose($conn);
            fclose($socket);
            exit(0);
        } else {
            // 父處理序：給 server 一點時間啟動
            usleep(100_000); // 0.1 秒

            $client = new TcpSocketClient($host, $port);
            $response = $client->send("hello test\n");

            $this->assertEquals("Echo: hello test\n", $response);

            pcntl_wait($status); // 等子程序結束
        }
    }
}