<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Service\AccompanyingPeriodWork;

use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
use Chill\PersonBundle\Service\AccompanyingPeriod\ProvideThirdPartiesAssociated as ProvideThirdPartiesAssociatedAccompanyingPeriod;
use Chill\ThirdPartyBundle\Entity\ThirdParty;

/**
 * Provide third parties associated with an accompanying period work.
 */
class ProvideThirdPartiesAssociated
{
    public function __construct(private readonly ProvideThirdPartiesAssociatedAccompanyingPeriod $thirdPartiesAssociated) {}

    /**
     * @return list<ThirdParty>
     */
    public function getThirdPartiesAssociated(AccompanyingPeriodWork $accompanyingPeriodWork): array
    {
        $thirdParties = $this->thirdPartiesAssociated->getThirdPartiesAssociated($accompanyingPeriodWork->getAccompanyingPeriod());

        if (null !== $tp = $accompanyingPeriodWork->getHandlingThierParty()) {
            $thirdParties[] = $tp;
        }

        foreach ($accompanyingPeriodWork->getThirdParties() as $thirdParty) {
            $thirdParties[] = $thirdParty;
        }

        return array_values(
            // filter objects to remove duplicates
            array_filter(
                $thirdParties,
                fn ($o, $k) => array_search($o, $thirdParties, true) === $k,
                ARRAY_FILTER_USE_BOTH
            )
        );
    }
}
