<?php declare(strict_types=1);
/**
 * @package messenger
 * @author kputyr
 * @date 23.03.2026
 */

namespace IMATHUZH\Messenger\Test;

use IMATHUZH\Messenger\AuthorizationToken;
use IMATHUZH\Messenger\SessionTokenManager;
use PHPUnit\Framework\TestCase;


class SessionTokenManagerTest extends TestCase
{
    public static function tokenProvider(): \Generator
    {
        $tsep = '/';
        $csep = ',';

        yield "pub/sub single group" => [
            ["psg{$tsep}pub" => "chA{$csep}chB", "psg{$tsep}sub" => "chC"],
            ["psg" => ["pub" => ["chA","chB"], "sub" => ["chC"] ]]
        ];
        yield "pub only single group" => [
            ["grp{$tsep}pub" => "chA{$csep}chB"],
            ["grp" => ["pub" => ["chA","chB"]]],
        ];
        yield "sub only single group" => [
            ["grp{$tsep}sub" => "chA{$csep}chB"],
            ["grp" => ["sub" => ["chA","chB"]]],
        ];
        yield "controller single group" => [
            ["grp{$tsep}ctl" => "chA{$csep}chB"],
            ["grp" => ["ctl" => ["chA","chB"]]],
        ];
        yield "multiple groups" => [
            ["grp1{$tsep}sub" => "chA{$csep}chB", "grp2{$tsep}sub" => "ch1{$csep}ch2", "grp1{$tsep}ctl" => "chX{$csep}all"],
            ["grp1" => ["sub" => ["chA","chB"], "ctl" => ["chX","all"]], "grp2" => ["sub" => ["ch1","ch2"]]],
        ];
    }

    public function testTokenExists(): void
    {
        $storage = [
            'rw' => ['rwtest1' => 'content'],
            'ro' => ['rotest1' => 'content']
        ];
        $tokenManager = new SessionTokenManager($storage['rw'], $storage['ro']);

        $this->assertFalse($tokenManager->tokenExists('rw'));
        $this->assertFalse($tokenManager->tokenExists('ro'));
        $this->assertTrue($tokenManager->tokenExists('rotest1'));
        $this->assertTrue($tokenManager->tokenExists('rwtest1'));
        $this->assertFalse($tokenManager->tokenExists('rotest2'));
        $this->assertFalse($tokenManager->tokenExists('rwtest2'));

        $storage['rw']['rwtest2'] = 'content';
        $storage['ro']['rotest2'] = 'content';
        $this->assertFalse($tokenManager->tokenExists('rotest2'));
        $this->assertTrue($tokenManager->tokenExists('rwtest2'));
    }

    public function testDeleteToken(): void
    {
        $storage = [
            'rw' => ['rwtest' => 'content'],
            'ro' => ['rotest' => 'content']
        ];
        $tokenManager = new SessionTokenManager($storage['rw'], $storage['ro']);

        // Existing token in rw store can be deleted
        $this->assertTrue($tokenManager->deleteToken('rwtest'));
        $this->assertEmpty($storage['rw']);

        // Existing token in ro store cannot be deleted
        $this->assertFalse($tokenManager->deleteToken('rotest'));

        // Deleting a non-existing token does not throw, but returns false
        $this->assertFalse($tokenManager->deleteToken('rwtest'));
        $this->assertFalse($tokenManager->deleteToken('nonexistent'));
    }

    /**
     * @dataProvider tokenProvider
     */
    public function testSaveToken(array $inStore, array $channels): void
    {
        $storage = [];
        $tokenManager = new SessionTokenManager($storage);

        $token = new AuthorizationToken($channels);
        $tokenId = $tokenManager->saveToken($token, 'token');

        $this->assertEquals('token', $tokenId);
        $this->assertArrayHasKey('token', $storage);
        parse_str($storage['token'], $persisted);
        $this->assertEquals($inStore, $persisted);

        $tokenId = $tokenManager->saveToken($token);
        $this->assertNotEquals('token', $tokenId);
        $this->assertArrayHasKey($tokenId, $storage);
        $this->assertEquals($storage['token'], $storage[$tokenId]);
    }

    /**
     * @dataProvider tokenProvider
     */
    public function testLoadToken(array $toStore, array $expanded): void
    {
        $storage = [ 'token' => http_build_query($toStore) ];
        $tokenManager = new SessionTokenManager($storage);

        $loaded = $tokenManager->loadToken('token');
        $this->assertSame($expanded, $loaded->toArray());
    }


    public function testLoadNonexistentTokenRaises(): void
    {
        $storage = [];
        $tokenManager = new SessionTokenManager($storage);

        $this->expectException(\Exception::class);
        $tokenManager->loadToken('nonexistent');
    }

}
