<?php

declare(strict_types=1);

namespace Tests\Integration;

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

final class ClientsLifecycleTest extends QdbTestCase
{
    public function testClientDetailAfterSubmit(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $code = $this->fixture()->clientCode;
        $res = $this->api()->withToken($token, 'GET', 'clients', null, [
            'clientCode' => $code,
            'detail'     => '1',
        ]);
        $this->assertApiOk($res);
        $this->assertSame($code, $res['data']['client']['clientCode'] ?? '');
        $this->assertNotEmpty($res['data']['questionnaires']);
    }

    public function testSupervisorCreatesClientForOwnCoach(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::SUPERVISOR_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $code = 'CLIENT-SV-' . bin2hex(random_bytes(2));
        $res = $this->api()->withToken($token, 'POST', 'clients', [
            'clientCode' => $code,
            'coachID'    => $this->fixture()->coachId,
        ]);
        $this->assertApiOk($res);
        $this->assertSame($code, $res['data']['clientCode']);
    }

    public function testAdminDeletesClient(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $code = 'CLIENT-DEL-' . bin2hex(random_bytes(2));
        $create = $this->api()->withToken($token, 'POST', 'clients', [
            'clientCode' => $code,
            'coachID'    => $this->fixture()->coachId,
        ]);
        $this->assertApiOk($create);

        $del = $this->api()->withToken($token, 'DELETE', 'clients', ['clientCode' => $code]);
        $this->assertApiOk($del);

        $list = $this->api()->withToken($token, 'GET', 'clients');
        $codes = array_column($list['data']['clients'], 'clientCode');
        $this->assertNotContains($code, $codes);
    }
}
