<?php

declare(strict_types=1);

namespace NoahVet\Reef\Business\Enumerator;

use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Jane\Exception\GetAllVeterinaryGroupUserBadRequestException;
use NoahVet\Reef\Jane\Model\VeterinaryGroupResponse;
use NoahVet\Reef\Jane\Model\VeterinaryGroupUserResponse;

class VeterinaryGroupTeamMembersEnumerator
{
    public function __construct(
        protected Client $client,
    ) {
    }

    /**
     * @param array{
     *     id?: string[],
     *     jobTitle?: string[],
     *     department?: string[],
     *     userId?: string[],
     *     veterinaryGroupId?: string[],
     *     veterinaryServiceOptionId?: string[],
     *     fromCreatedDate?: string[],
     *     fromUpdatedDate?: string[],
     *     fromEntryDate?: string[],
     *     fromExitDate?: string[],
     *     fromServiceSubscriptionStartDate?: string[],
     *     fromServiceSubscriptionEndDate?: string[],
     *     toCreatedDate?: string[],
     *     toUpdatedDate?: string[],
     *     toEntryDate?: string[],
     *     toExitDate?: string[],
     *     toServiceSubscriptionStartDate?: string[],
     *     toServiceSubscriptionEndDate?: string[],
     *     sortCreatedDate?: string,
     *     sortUpdatedDatesortCreatedDate?: string,
     *     sortEntryDatesortCreatedDate?: string,
     *     sortExitDatesortCreatedDate?: string,
     *     sortJobTitlesortCreatedDate?: string
     *  } $filters
     *
     * @return \Generator<VeterinaryGroupUserResponse>
     *
     * @see Client::getAllVeterinaryGroupUser
     */
    public function enumerateAll(
        array $filters = [],
        int $querySize = 50,
    ): \Generator {
        for ($page = 0; true; ++$page) {
            try {
                $teamMembers = $this->client->getAllVeterinaryGroupUser(
                    \array_merge($filters, ['page' => $page, 'limit' => $querySize]),
                );

                \assert(\is_array($teamMembers));

                foreach ($teamMembers as $teamMember) {
                    yield $teamMember;
                }

                if (\count($teamMembers) < $querySize) {
                    break;
                }
            } catch (GetAllVeterinaryGroupUserBadRequestException) {
                // End of enumeration
                break;
            }
        }
    }

    /**
     * @param array<int, VeterinaryGroupResponse> $groups
     *
     * @return array<string, array<VeterinaryGroupUserResponse>>
     */
    public function getTeamMembers(
        array $groups,
        int $querySize = 50,
        ?\DateTimeImmutable $now = null,
    ): array {
        $nowStr = ($now ?? new \DateTimeImmutable())->format('c');
        $uuids = $this->extractUuids($groups);

        $filters = [
            'veterinaryGroupId' => $uuids,
            'toEntryDate' => [$nowStr, 'null'],
            'fromExitDate' => [$nowStr, 'null'],
        ];

        return \array_reduce(
            \iterator_to_array($this->enumerateAll($filters, $querySize)),
            function (array $carry, VeterinaryGroupUserResponse $item): array {
                $establishmentId = $item->getVeterinaryGroup()?->getId();

                if (null !== $establishmentId) {
                    $carry[$establishmentId][] = $item;
                }

                return $carry;
            },
            [],
        );
    }

    /**
     * @param array<int, VeterinaryGroupResponse> $groups
     *
     * @return array<int, string>
     */
    protected function extractUuids(array $groups): array
    {
        return \array_map(
            fn (VeterinaryGroupResponse $grp): string => $grp->getId(),
            $groups,
        );
    }
}
