<?php

use PHPUnit\Framework\TestCase;

class UtilsTest extends TestCase {
	public function test_response_error_returns_json_with_status_false(): void {
		$utils = new \SHServ\Utils();
		$json = $utils -> response_error('not_found');

		$data = json_decode($json, true);
		$this -> assertFalse($data['status']);
		$this -> assertSame('not_found', $data['error_alias']);
		$this -> assertSame('Not found', $data['msg']);
	}

	public function test_response_error_includes_failed_fields_and_extra(): void {
		$utils = new \SHServ\Utils();
		$json = $utils -> response_error('invalid_request', ['field1'], ['retry_after' => 30], 422);

		$data = json_decode($json, true);
		$this -> assertSame(['field1'], $data['failed_fields']);
		$this -> assertSame(30, $data['retry_after']);
	}

	public function test_response_success_returns_json_with_status_true(): void {
		$utils = new \SHServ\Utils();
		$json = $utils -> response_success(['id' => 5]);

		$data = json_decode($json, true);
		$this -> assertTrue($data['status']);
		$this -> assertSame(['id' => 5], $data['data']);
	}

	public function test_table_row_is_exists_finds_row(): void {
		$tb = app() -> thin_builder;
		$tb -> query("CREATE TABLE IF NOT EXISTS test_exists (id INTEGER PRIMARY KEY, name VARCHAR(50))");
		$tb -> insert('test_exists', ['name' => 'Alice']);

		$utils = new \SHServ\Utils();
		$this -> assertTrue($utils -> table_row_is_exists($tb, 'test_exists', 'name', 'Alice'));
		$this -> assertFalse($utils -> table_row_is_exists($tb, 'test_exists', 'name', 'Bob'));

		$tb -> query("DROP TABLE IF EXISTS test_exists");
	}

	public function test_generate_token_length_and_format(): void {
		$utils = new \SHServ\Utils();

		$token = $utils -> generate_token(16);
		$this -> assertSame(16, strlen($token));
		$this -> assertMatchesRegularExpression('/^[a-f0-9]+$/', $token);

		$token32 = $utils -> generate_token(32);
		$this -> assertSame(32, strlen($token32));
	}

	public function test_dayname_translate(): void {
		$utils = new \SHServ\Utils();
		$this -> assertSame('понедельник', $utils -> dayname_translate('monday', 'ru'));
		$this -> assertSame('вторник', $utils -> dayname_translate('tuesday', 'ru'));
		$this -> assertSame('sunday', $utils -> dayname_translate('sunday', 'en'));
		$this -> assertNull($utils -> dayname_translate('unknown', 'ru'));
	}

	public function test_fast_ping_tcp_returns_bool(): void {
		$utils = new \SHServ\Utils();
		$result = $utils -> fast_ping_tcp('127.0.0.1', 9999, 0.1);
		$this -> assertIsBool($result);
	}
}
