<?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\ActivityBundle\EntityListener;

use Chill\ActivityBundle\Entity\Activity;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Doctrine\ORM\EntityManagerInterface;

class ActivityEntityListener
{
    public function __construct(private readonly EntityManagerInterface $em, private readonly AccompanyingPeriodWorkRepository $workRepository) {}

    public function persistActionToCourse(Activity $activity)
    {
        if ($activity->getAccompanyingPeriod() instanceof AccompanyingPeriod) {
            $period = $activity->getAccompanyingPeriod();

            $accompanyingCourseWorks = $this->workRepository->findByAccompanyingPeriod($period);
            $periodActions = [];
            $now = new \DateTimeImmutable();

            foreach ($accompanyingCourseWorks as $key => $work) {
                // take only the actions which are still opened
                if (null === $work->getEndDate() || $work->getEndDate() > ($activity->getDate() ?? $now)) {
                    $periodActions[$key] = spl_object_hash($work->getSocialAction());
                }
            }

            $associatedPersons = $activity->getPersonsAssociated();
            $associatedThirdparties = $activity->getThirdParties();

            foreach ($activity->getSocialActions() as $action) {
                if (\in_array(spl_object_hash($action), $periodActions, true)) {
                    continue;
                }
                $newAction = new AccompanyingPeriodWork();
                $newAction->setSocialAction($action);
                $period->addWork($newAction);

                $date = \DateTimeImmutable::createFromMutable($activity->getDate());
                $newAction->setStartDate($date);

                foreach ($associatedPersons as $person) {
                    $newAction->addPerson($person);
                }

                $this->em->persist($newAction);
                $this->em->flush();
            }
        }
    }
}
