<?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 testClientListIncludesFollowupNote(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $code = $this->fixture()->clientCode;
        $note = 'Clients list note check';

        $save = $this->api()->withToken($token, 'PUT', 'analytics', [
            'clientCode' => $code,
            'note'       => $note,
        ]);
        $this->assertApiOk($save);

        $list = $this->api()->withToken($token, 'GET', 'clients', null, [
            'archiveFilter' => 'all',
        ]);
        $this->assertApiOk($list);
        $match = null;
        foreach ($list['data']['clients'] ?? [] as $row) {
            if (($row['clientCode'] ?? '') === $code) {
                $match = $row;
                break;
            }
        }
        $this->assertNotNull($match);
        $this->assertSame($note, $match['note'] ?? null);
    }

    public function testArchiveHidesClientFromListsAndFollowUp(): void
    {
        $this->submitFixtureQuestionnaire();
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $code = $this->fixture()->clientCode;

        $archive = $this->api()->withToken($token, 'PATCH', 'clients', [
            'clientCode' => $code,
            'archived'   => true,
        ]);
        $this->assertApiOk($archive);
        $this->assertSame(1, (int)($archive['data']['archived'] ?? 0));

        $active = $this->api()->withToken($token, 'GET', 'clients');
        $this->assertApiOk($active);
        $activeCodes = array_column($active['data']['clients'], 'clientCode');
        $this->assertNotContains($code, $activeCodes);

        $archivedOnly = $this->api()->withToken($token, 'GET', 'clients', null, [
            'archiveFilter' => 'archived',
        ]);
        $this->assertApiOk($archivedOnly);
        $archivedCodes = array_column($archivedOnly['data']['clients'], 'clientCode');
        $this->assertContains($code, $archivedCodes);

        $assign = $this->api()->withToken($token, 'GET', 'assignments');
        $this->assertApiOk($assign);
        $assignCodes = array_column($assign['data']['clients'], 'clientCode');
        $this->assertNotContains($code, $assignCodes);

        $stale = $this->api()->withToken($token, 'GET', 'analytics', null, ['staleClients' => '1']);
        $this->assertApiOk($stale);
        $staleCodes = array_column($stale['data']['clients'], 'clientCode');
        $this->assertNotContains($code, $staleCodes);

        $restore = $this->api()->withToken($token, 'PATCH', 'clients', [
            'clientCode' => $code,
            'archived'   => false,
        ]);
        $this->assertApiOk($restore);
        $this->assertSame(0, (int)($restore['data']['archived'] ?? 1));

        $activeAgain = $this->api()->withToken($token, 'GET', 'clients');
        $this->assertApiOk($activeAgain);
        $this->assertContains($code, array_column($activeAgain['data']['clients'], '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);
    }

    public function testAdminCreatesClientRange(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $prefix = 'RANGE-' . bin2hex(random_bytes(2)) . '-';

        $res = $this->api()->withToken($token, 'POST', 'clients', [
            'bulk'     => true,
            'fromCode' => $prefix . '001',
            'toCode'   => $prefix . '003',
            'coachID'  => $this->fixture()->coachId,
        ]);
        $this->assertApiOk($res);
        $this->assertSame(3, $res['data']['createdCount']);
        $this->assertSame(
            [$prefix . '001', $prefix . '002', $prefix . '003'],
            $res['data']['created'],
        );

        $list = $this->api()->withToken($token, 'GET', 'clients');
        $codes = array_column($list['data']['clients'], 'clientCode');
        foreach ([$prefix . '001', $prefix . '002', $prefix . '003'] as $code) {
            $this->assertContains($code, $codes);
        }
    }

    public function testBulkCreateSkipsDuplicates(): void
    {
        $token = $this->api()->loginWebAndGetToken(
            DatabaseSeeder::ADMIN_USERNAME,
            DatabaseSeeder::PASSWORD
        )['token'];
        $prefix = 'DUP-' . bin2hex(random_bytes(2)) . '-';
        $existing = $prefix . '002';

        $single = $this->api()->withToken($token, 'POST', 'clients', [
            'clientCode' => $existing,
            'coachID'    => $this->fixture()->coachId,
        ]);
        $this->assertApiOk($single);

        $res = $this->api()->withToken($token, 'POST', 'clients', [
            'bulk'     => true,
            'fromCode' => $prefix . '001',
            'toCode'   => $prefix . '003',
            'coachID'  => $this->fixture()->coachId,
        ]);
        $this->assertApiOk($res);
        $this->assertSame(2, $res['data']['createdCount']);
        $this->assertSame(1, $res['data']['skippedCount']);
        $this->assertSame($existing, $res['data']['skipped'][0]['clientCode']);
    }
}
