<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class AppQuestionnairesBulkTest extends QdbTestCase
{
    public function testCoachLoadsBulkAnswers(): void
    {
        $this->submitFixtureQuestionnaire();
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $res = $this->api()->withMobileToken($login['token'], 'GET', 'app_questionnaires', null, [
            'answersBulk' => '1',
        ]);
        $this->assertApiOk($res);
        $this->assertTrue($res['data']['encrypted'] ?? false);
        $plain = qdb_decrypt_sensitive_envelope($res['data'], $login['token']);
        $payload = json_decode($plain, true, 512, JSON_THROW_ON_ERROR);
        $this->assertIsArray($payload['clients'] ?? null);
        $found = null;
        foreach ($payload['clients'] as $row) {
            if (($row['clientCode'] ?? '') === $this->fixture()->clientCode) {
                $found = $row;
                break;
            }
        }
        $this->assertNotNull($found, 'fixture client missing from bulk payload');
        $this->assertNotEmpty($found['questionnaires'] ?? []);
        $qn = $found['questionnaires'][0];
        $this->assertSame($this->fixture()->questionnaireId, $qn['questionnaireID'] ?? null);
        $this->assertNotEmpty($qn['answers'] ?? []);
    }

    public function testReadDbOpenUsesCacheOnSecondCall(): void
    {
        [$pdo1, $tmp1] = qdb_open(false);
        [$pdo2, $tmp2] = qdb_open(false);
        $this->assertSame(QDB_READONLY_CACHE_HANDLE, $tmp1);
        $this->assertSame(QDB_READONLY_CACHE_HANDLE, $tmp2);
        $this->assertSame($pdo1, $pdo2);
        qdb_discard($tmp1, null);
        qdb_discard($tmp2, null);
    }
}
