<?php

namespace Telegram;

use Openguru\OpenCartFramework\Telegram\TelegramInitDataDecoder;
use Openguru\OpenCartFramework\Telegram\TelegramService;
use Tests\TestCase;

class TelegramServiceTest extends TestCase
{
    private TelegramService $service;

    protected function setUp(): void
    {
        parent::setUp();
        $this->service = new TelegramService(
            new TelegramInitDataDecoder(),
            $this->getNullLogger(),
        );
    }

    public function testDoesNotEscapeNormalCharacters(): void
    {
        $this->assertEquals('hello world', $this->service->escapeTgSpecialCharacters('hello world'));
    }

    public function testEscapesSingleSpecialCharacters(): void
    {
        $this->assertEquals('\_', $this->service->escapeTgSpecialCharacters('_'));
        $this->assertEquals('\#', $this->service->escapeTgSpecialCharacters('#'));
        $this->assertEquals('\+', $this->service->escapeTgSpecialCharacters('+'));
        $this->assertEquals('\(', $this->service->escapeTgSpecialCharacters('('));
        $this->assertEquals('\)', $this->service->escapeTgSpecialCharacters(')'));
        $this->assertEquals('\!', $this->service->escapeTgSpecialCharacters('!'));
    }

    public function testDoesNotDoubleEscapeAlreadyEscaped(): void
    {
        $this->assertEquals('\#', $this->service->escapeTgSpecialCharacters('\#'));
        $this->assertEquals('\\\\', $this->service->escapeTgSpecialCharacters('\\\\')); // двойной бэкслеш остаётся двойным
    }

    public function testEscapesInsideText(): void
    {
        $this->assertEquals('price is 100\#', $this->service->escapeTgSpecialCharacters('price is 100#'));
        $this->assertEquals('a\(b\)c', $this->service->escapeTgSpecialCharacters('a(b)c'));
        $this->assertEquals('a\+b', $this->service->escapeTgSpecialCharacters('a+b'));
    }

    public function testEscapesBackslashAtEnd(): void
    {
        // висячий бэкслеш должен быть продублирован
        $this->assertEquals('backslash\\\\', $this->service->escapeTgSpecialCharacters('backslash\\'));
    }

    public function testDoesNotEscapeEscapedSpecialCharacter(): void
    {
        // \# должен остаться \#
        $this->assertEquals('\#tag', $this->service->escapeTgSpecialCharacters('\#tag'));
    }

    public function testMultipleSpecialCharactersInRow(): void
    {
        $this->assertEquals('\#\+\=', $this->service->escapeTgSpecialCharacters('#+='));
        $this->assertEquals('\#\+\=text', $this->service->escapeTgSpecialCharacters('#+=text'));
    }

    public function testEmojiAndMultibyteCharactersAreUntouched(): void
    {
        $this->assertEquals('Привет 👋', $this->service->escapeTgSpecialCharacters('Привет 👋'));
        $this->assertEquals('emoji\#', $this->service->escapeTgSpecialCharacters('emoji#'));
    }
}
