<?php

declare(strict_types=1);

namespace Tests\Integration;

use Tests\Support\DatabaseSeeder;
use Tests\Support\QdbTestCase;

final class UsersTest extends QdbTestCase
{
    public function testAdminListsUsers(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'GET', 'users');
        $this->assertApiOk($res);
        $this->assertGreaterThanOrEqual(3, count($res['data']['users']));
    }

    public function testRevokeUserSessions(): void
    {
        $admin = $this->adminToken();
        $coach = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );

        $f = $this->fixture();
        $res = $this->api()->withToken($admin, 'PUT', 'users', [
            'action' => 'revokeSessions',
            'userID' => $f->coachUserId,
        ]);
        $this->assertApiOk($res);
        $this->assertGreaterThanOrEqual(1, $res['data']['revokedSessions']);

        $dead = $this->api()->withMobileToken($coach['token'], 'GET', 'session');
        $this->assertApiError($dead, 'UNAUTHORIZED', 401);
    }

    public function testCannotRevokeOwnSessions(): void
    {
        $login = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $res = $this->api()->withToken($login['token'], 'PUT', 'users', [
            'action' => 'revokeSessions',
            'userID' => $this->fixture()->adminUserId,
        ]);
        $this->assertApiError($res, 'FORBIDDEN', 400);
    }
}
