<?php

namespace NoahVet\Reef\Business\Model\Factory;

use NoahVet\Reef\Business\Enumerator\VeterinaryGroupTeamMembersEnumerator;
use NoahVet\Reef\Business\Model\GroupWithTeam;
use NoahVet\Reef\Business\Model\TeamMember;
use NoahVet\Reef\Jane\Model\VeterinaryGroupResponse;
use NoahVet\Reef\Jane\Model\VeterinaryGroupUserResponse;

class GroupWithTeamFactory
{
    public function __construct(
        protected VeterinaryGroupTeamMembersEnumerator $groupTeamMembersEnumerator,
        protected TeamMemberFactory $teamMemberFactory,
    ) {
    }

    /**
     * @param array<int, VeterinaryGroupResponse> $groups
     *
     * @return GroupWithTeam[]
     */
    public function createBatch(array $groups): array
    {
        $teamMembers = $this->groupTeamMembersEnumerator->getTeamMembers($groups);

        return \array_map(
            fn (VeterinaryGroupResponse $est): GroupWithTeam => $this->build(
                $est,
                $teamMembers[$est->getId()] ?? [],
            ),
            $groups,
        );
    }

    public function create(
        VeterinaryGroupResponse $group,
    ): GroupWithTeam {
        $teamMembers = $this->groupTeamMembersEnumerator->getTeamMembers([$group]);

        return $this->build(
            $group,
            $teamMembers[$group->getId()] ?? [],
        );
    }

    /**
     * @param array<VeterinaryGroupUserResponse> $teamMembers
     */
    protected function build(
        VeterinaryGroupResponse $group,
        array $teamMembers,
    ): GroupWithTeam {
        return new GroupWithTeam(
            $group->getId(),
            $group->getGroupCode() ?? '',
            \array_map(
                fn (VeterinaryGroupUserResponse $teamMember): TeamMember => $this->teamMemberFactory->create(
                    $teamMember,
                ),
                $teamMembers,
            ),
        );
    }
}
