<?php

declare(strict_types=1);

namespace Tests\Integration;

use Tests\Support\QdbTestCase;

final class ChangePasswordTest extends QdbTestCase
{
    public function testMustChangePasswordFlow(): void
    {
        [$pdo, $tmpDb, $lockFp] = qdb_open(true);
        $f = $this->fixture();
        $pdo->prepare('UPDATE users SET mustChangePassword = 1 WHERE userID = :uid')
            ->execute([':uid' => $f->supervisorUserId]);
        qdb_save($tmpDb, $lockFp);

        $login = $this->api()->loginWeb(
            \Tests\Support\DatabaseSeeder::SUPERVISOR_USERNAME,
            \Tests\Support\DatabaseSeeder::PASSWORD
        );
        $this->assertApiOk($login);
        $this->assertTrue($login['data']['mustChangePassword']);
        $tempToken = $login['data']['token'];

        $change = $this->api()->request('POST', 'auth/change-password', [
            'username'     => 'test_supervisor',
            'old_password' => 'TestPass1!',
            'new_password' => 'NewPass2!',
        ], ['Authorization' => 'Bearer ' . $tempToken, 'X-QDB-Client' => 'web']);
        $this->assertApiOk($change);
        $this->assertNotEmpty($change['data']['token']);

        $session = $this->api()->withToken($change['data']['token'], 'GET', 'session');
        $this->assertApiOk($session);
        $this->assertFalse($session['data']['mustChangePassword'] ?? false);
    }
}
