<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class ResultsAnalyticsTest extends QdbTestCase
{
    public function testResultsIncludeSubmittedClient(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $f = $this->fixture();

        $res = $this->api()->withToken($token, 'GET', 'results', null, [
            'questionnaireID' => $f->questionnaireId,
        ]);
        $this->assertApiOk($res);
        $byCode = [];
        foreach ($res['data']['clients'] as $row) {
            $byCode[$row['clientCode']] = $row;
        }
        $this->assertArrayHasKey($f->clientCode, $byCode);
        $this->assertSame('completed', $byCode[$f->clientCode]['status']);
        $this->assertNotNull($byCode[$f->clientCode]['completedAt']);
    }

    public function testAnalyticsOverviewForSupervisor(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::SUPERVISOR_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];

        $res = $this->api()->withToken($token, 'GET', 'analytics', null, ['overview' => '1']);
        $this->assertApiOk($res);
        $this->assertArrayHasKey('clientCount', $res['data']);
        $this->assertArrayHasKey('questionnaires', $res['data']);
        $this->assertGreaterThan(0, $res['data']['clientCount']);
    }

    public function testStaleClientsList(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::SUPERVISOR_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $res = $this->api()->withToken($token, 'GET', 'analytics', null, ['staleClients' => '1']);
        $this->assertApiOk($res);
        $this->assertArrayHasKey('clients', $res['data']);
    }

    public function testFollowUpNoteRoundTrip(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->adminToken();
        $code = $this->fixture()->clientCode;
        $note = 'Call back next week';
        $save = $this->api()->withToken($token, 'PUT', 'analytics', [
            'clientCode' => $code,
            'note'       => $note,
        ]);
        $this->assertApiOk($save);
        $this->assertSame($note, $save['data']['note']);

        $stale = $this->api()->withToken($token, 'GET', 'analytics', null, ['staleClients' => '1']);
        $this->assertApiOk($stale);
        $match = null;
        foreach ($stale['data']['clients'] as $row) {
            if (($row['clientCode'] ?? '') === $code) {
                $match = $row;
                break;
            }
        }
        $this->assertIsArray($match);
        $this->assertSame($note, $match['note']);
    }
}
