<?php

namespace NoahVet\Reef\Infrastructure\Security\BSM;

use NoahVet\Reef\Application\Business\AbstractWithTeamFactory;
use NoahVet\Reef\Domain\Business\Model\PublisherWithTeam;
use NoahVet\Reef\Domain\Business\Model\TeamMember;
use NoahVet\Reef\Infrastructure\Business\BSM\PublisherTeamMembersEnumerator;

class PublisherWithTeamFactory extends AbstractWithTeamFactory
{
    public function __construct(
        private readonly PublisherTeamMembersEnumerator $teamMembersEnumerator,
    ) {
        $teamMemberMapper = static function (object $u): TeamMember {
            $entryDate = $u->getEntryDate(); // @phpstan-ignore method.notFound
            $exitDate = $u->getExitDate(); // @phpstan-ignore method.notFound

            return new TeamMember(
                ($u->getUser() ?? throw new \LogicException('Missing user on PublisherUserResponse'))->getId(), // @phpstan-ignore method.notFound
                $u->getJobTitle(), // @phpstan-ignore method.notFound
                null !== $entryDate ? \DateTimeImmutable::createFromMutable($entryDate) : null,
                null !== $exitDate ? \DateTimeImmutable::createFromMutable($exitDate) : null,
            );
        };
        /* @phpstan-ignore method.notFound */
        $entityIdExtractor = static fn (object $e): string => $e->getId();

        parent::__construct($teamMemberMapper, $entityIdExtractor);
    }

    #[\Override]
    protected function build(mixed $entity, array $userResponses): PublisherWithTeam
    {
        return new PublisherWithTeam(
            $entity->getId(),
            $entity->getCode(),
            \array_map(fn (object $u): TeamMember => ($this->teamMemberMapper)($u), $userResponses),
        );
    }

    #[\Override]
    protected function getTeamMembers(array $entities): array
    {
        return $this->teamMembersEnumerator->getTeamMembers(\array_values($entities));
    }
}
