<?php

declare(strict_types=1);

namespace NoahVet\Reef\Business\Model\Factory;

use NoahVet\Reef\Business\Enumerator\VeterinaryEstablishmentTeamMembersEnumerator;
use NoahVet\Reef\Business\Model\EstablishmentWithTeam;
use NoahVet\Reef\Business\Model\TeamMember;
use NoahVet\Reef\Jane\Model\VeterinaryEstablishmentResponse;
use NoahVet\Reef\Jane\Model\VeterinaryEstablishmentUserResponse;

class EstablishmentWithTeamFactory
{
    public function __construct(
        protected VeterinaryEstablishmentTeamMembersEnumerator $establishmentTeamMembersEnumerator,
        protected TeamMemberFactory $teamMemberFactory,
    ) {
    }

    /**
     * @param array<int, VeterinaryEstablishmentResponse> $establishments
     *
     * @return EstablishmentWithTeam[]
     */
    public function createBatch(array $establishments): array
    {
        $teamMembers = $this->establishmentTeamMembersEnumerator->getTeamMembers($establishments);

        return \array_map(
            fn (VeterinaryEstablishmentResponse $est): EstablishmentWithTeam => $this->build(
                $est,
                $teamMembers[$est->getId()] ?? [],
            ),
            $establishments,
        );
    }

    public function create(
        VeterinaryEstablishmentResponse $establishment,
    ): EstablishmentWithTeam {
        $teamMembers = $this->establishmentTeamMembersEnumerator->getTeamMembers([$establishment]);

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

    /**
     * @param array<VeterinaryEstablishmentUserResponse> $teamMembers
     */
    protected function build(
        VeterinaryEstablishmentResponse $establishment,
        array $teamMembers,
    ): EstablishmentWithTeam {
        return new EstablishmentWithTeam(
            $establishment->getId(),
            $establishment->getPrivilegedCode(),
            \array_map(
                fn (VeterinaryEstablishmentUserResponse $member): TeamMember => $this->teamMemberFactory->create(
                    $member,
                ),
                $teamMembers,
            ),
        );
    }
}
