<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class AppQuestionnairesTest extends QdbTestCase
{
    public function testCoachSubmitsQuestionnaire(): void
    {
        $res = $this->submitFixtureQuestionnaire();
        $this->assertApiOk($res);
        $this->assertTrue($res['data']['submitted'] ?? false);
    }

    public function testCoachLoadsQuestionnaireDefinition(): void
    {
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $res = $this->api()->withMobileToken($login['token'], 'GET', 'app_questionnaires', null, [
            'id' => $this->fixture()->questionnaireId,
        ]);
        $this->assertApiOk($res);
        $this->assertNotEmpty($res['data']['questions']);

        $glass = null;
        foreach ($res['data']['questions'] as $q) {
            if (($q['layout'] ?? '') === 'glass_scale_question') {
                $glass = $q;
                break;
            }
        }
        $this->assertNotNull($glass);
        $this->assertIsArray($glass['glassSymptoms'] ?? null);
        $symptomKeys = array_column($glass['glassSymptoms'], 'key');
        $this->assertContains($this->fixture()->glassSymptomKey, $symptomKeys);
    }

    public function testCoachListsAssignedClients(): void
    {
        $this->submitFixtureQuestionnaire();
        $login = $this->api()->loginMobileAndGetToken(
            DatabaseSeeder::COACH_USERNAME,
            DatabaseSeeder::PASSWORD
        );
        $res = $this->api()->withMobileToken($login['token'], 'GET', 'app_questionnaires', null, [
            'clients' => '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);
        $codes = array_column($payload['clients'], 'clientCode');
        $this->assertContains($this->fixture()->clientCode, $codes);
    }
}
