<?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\Workflow;

use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\MainBundle\Workflow\EntityWorkflowHandlerInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodWorkVoter;
use Chill\PersonBundle\Service\AccompanyingPeriodWork\ProvidePersonsAssociated;
use Chill\PersonBundle\Service\AccompanyingPeriodWork\ProvideThirdPartiesAssociated;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * @implements EntityWorkflowHandlerInterface<AccompanyingPeriodWork>
 */
readonly class AccompanyingPeriodWorkWorkflowHandler implements EntityWorkflowHandlerInterface
{
    public function __construct(
        private AccompanyingPeriodWorkRepository $repository,
        private EntityWorkflowRepository $workflowRepository,
        private TranslatableStringHelperInterface $translatableStringHelper,
        private TranslatorInterface $translator,
        private ProvideThirdPartiesAssociated $thirdPartiesAssociated,
        private ProvidePersonsAssociated $providePersonsAssociated,
    ) {}

    public function getDeletionRoles(): array
    {
        return [AccompanyingPeriodWorkVoter::DELETE];
    }

    public function getEntityData(EntityWorkflow $entityWorkflow, array $options = []): array
    {
        return [
            'persons' => $this->getRelatedEntity($entityWorkflow)?->getPersons() ?? [],
        ];
    }

    public function getEntityTitle(EntityWorkflow $entityWorkflow, array $options = []): string
    {
        $work = $this->getRelatedEntity($entityWorkflow);

        if (null === $work) {
            return $this->translator->trans('workflow.SocialAction deleted');
        }

        return
            $this->translator->trans('entity_display_title.Work (n°%w%)', ['%w%' => $entityWorkflow->getRelatedEntityId()])
            .' - '.$this->translatableStringHelper->localize($work->getSocialAction()->getTitle());
    }

    public function getRelatedEntity(EntityWorkflow $entityWorkflow): ?AccompanyingPeriodWork
    {
        return $this->repository->find($entityWorkflow->getRelatedEntityId());
    }

    public function getRelatedAccompanyingPeriod(EntityWorkflow $entityWorkflow): ?AccompanyingPeriod
    {
        return $this->getRelatedEntity($entityWorkflow)?->getAccompanyingPeriod();
    }

    public function getRelatedObjects(object $object): array
    {
        $relateds = [];
        $relateds[] = ['entityClass' => AccompanyingPeriodWork::class, 'entityId' => $object->getId()];

        foreach ($object->getAccompanyingPeriodWorkEvaluations() as $evaluation) {
            $relateds[] = ['entityClass' => AccompanyingPeriodWorkEvaluation::class, 'entityId' => $evaluation->getId()];

            foreach ($evaluation->getDocuments() as $doc) {
                $relateds[] = ['entityClass' => AccompanyingPeriodWorkEvaluationDocument::class, 'entityId' => $doc->getId()];
            }
        }

        return $relateds;
    }

    public function getRoleShow(EntityWorkflow $entityWorkflow): ?string
    {
        return null;
    }

    public function getSuggestedUsers(EntityWorkflow $entityWorkflow): array
    {
        $related = $this->getRelatedEntity($entityWorkflow);

        if (null === $related) {
            return [];
        }

        $users = [];
        if (null !== $referrer = $related->getAccompanyingPeriod()
            ->getUser()
        ) {
            $users[] = $referrer;
        }

        foreach ($related->getReferrersHistoryCurrent() as $referrerHistory
        ) {
            $users[] = $referrerHistory->getUser();
        }

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

    public function getTemplate(EntityWorkflow $entityWorkflow, array $options = []): string
    {
        return '@ChillPerson/Workflow/_accompanying_period_work.html.twig';
    }

    public function getTemplateData(EntityWorkflow $entityWorkflow, array $options = []): array
    {
        return [
            'entity_workflow' => $entityWorkflow,
            'work' => $this->getRelatedEntity($entityWorkflow),
        ];
    }

    public function isObjectSupported(object $object): bool
    {
        return $object instanceof AccompanyingPeriodWork;
    }

    public function supports(EntityWorkflow $entityWorkflow, array $options = []): bool
    {
        return AccompanyingPeriodWork::class === $entityWorkflow->getRelatedEntityClass();
    }

    public function supportsFreeze(EntityWorkflow $entityWorkflow, array $options = []): bool
    {
        return false;
    }

    public function findByRelatedEntity(object $object): array
    {
        if (!$object instanceof AccompanyingPeriodWork) {
            return [];
        }

        return $this->workflowRepository->findByRelatedEntity(AccompanyingPeriodWork::class, $object->getId());
    }

    public function getSuggestedPersons(EntityWorkflow $entityWorkflow): array
    {
        $related = $this->getRelatedEntity($entityWorkflow);

        if (null === $related) {
            return [];
        }

        return $this->providePersonsAssociated->getPersonsAssociated($related);
    }

    public function getSuggestedThirdParties(EntityWorkflow $entityWorkflow): array
    {
        $related = $this->getRelatedEntity($entityWorkflow);

        if (null === $related) {
            return [];
        }

        return $this->thirdPartiesAssociated->getThirdPartiesAssociated($related);
    }
}
