<?php

namespace NoahVet\Reef\Business\Model\Factory;

use NoahVet\Reef\Business\Enumerator\ManufacturerTeamMembersEnumerator;
use NoahVet\Reef\Business\Model\ManufacturerWithTeam;
use NoahVet\Reef\Jane\Model\ManufacturerResponseItem;
use NoahVet\Reef\Jane\Model\ManufacturerUserResponseItem;

class ManufacturerWithTeamFactory
{
    public function __construct(
        protected ManufacturerTeamMembersEnumerator $manufacturerTeamMembersEnumerator,
        protected TeamMemberFactory $teamMemberFactory,
    ) {
    }

    /**
     * @param ManufacturerResponseItem[] $manufacturers
     *
     * @return ManufacturerWithTeam[]
     */
    public function createBatch(array $manufacturers): array
    {
        $teamMembers = $this->manufacturerTeamMembersEnumerator->getTeamMembers($manufacturers);

        return \array_map(fn ($m) => $this->build($m, $teamMembers[$m->getId()] ?? []), $manufacturers);
    }

    public function create(ManufacturerResponseItem $manufacturer): ManufacturerWithTeam
    {
        $teamMembers = $this->manufacturerTeamMembersEnumerator->getTeamMembers([$manufacturer]);

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

    /**
     * @param array<ManufacturerUserResponseItem> $teamMembers
     */
    protected function build(
        ManufacturerResponseItem $manufacturer,
        array $teamMembers,
    ): ManufacturerWithTeam {
        return new ManufacturerWithTeam(
            $manufacturer->getId(),
            $manufacturer->getCode(),
            \array_map(fn ($teamMember) => $this->teamMemberFactory->create($teamMember), $teamMembers),
        );
    }
}
