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

use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\AddressReference;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Event\Person\PersonAddressMoveEvent;
use Chill\PersonBundle\Repository\Household\HouseholdACLAwareRepositoryInterface;
use Chill\PersonBundle\Repository\Household\HouseholdRepository;
use Chill\PersonBundle\Security\Authorization\HouseholdVoter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

class HouseholdApiController extends ApiController
{
    public function __construct(private readonly EventDispatcherInterface $eventDispatcher, private readonly HouseholdRepository $householdRepository, private readonly HouseholdACLAwareRepositoryInterface $householdACLAwareRepository, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    /**
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    #[Route(path: '/api/1.0/person/household/by-address-reference/{id}.json', name: 'chill_api_person_household_by_address_reference')]
    public function getHouseholdByAddressReference(AddressReference $addressReference): Response
    {
        $this->denyAccessUnlessGranted('ROLE_USER');

        $total = $this->householdACLAwareRepository->countByAddressReference($addressReference);
        $paginator = $this->getPaginatorFactory()->create($total);
        $households = $this->householdACLAwareRepository->findByAddressReference(
            $addressReference,
            $paginator->getCurrentPageFirstItemNumber(),
            $paginator->getItemsPerPage()
        );
        $collection = new Collection($households, $paginator);

        return $this->json($collection, Response::HTTP_OK, [], [
            AbstractNormalizer::GROUPS => ['read'],
        ]);
    }

    /**
     * Add an address to a household.
     */
    #[Route(path: '/api/1.0/person/household/{id}/address.{_format}', name: 'chill_api_single_household_address', methods: ['POST'], requirements: ['_format' => 'json'])]
    public function householdAddressApi(Household $household, Request $request, string $_format): Response
    {
        $this->denyAccessUnlessGranted(HouseholdVoter::EDIT, $household);

        /** @var Address $address */
        $address = $this->getSerializer()->deserialize($request->getContent(), Address::class, $_format, [
            AbstractNormalizer::GROUPS => ['write'],
        ]);

        $household->addAddress($address);

        foreach ($household->getMembersOnRange(
            \DateTimeImmutable::createFromMutable($address->getValidFrom()),
            null === $address->getValidTo() ? null :
                \DateTimeImmutable::createFromMutable($address->getValidTo())
        ) as $member) {
            /** @var HouseholdMember $member */
            $event = new PersonAddressMoveEvent($member->getPerson());
            $event
                ->setPreviousAddress($household->getPreviousAddressOf($address))
                ->setNextAddress($address);
            $this->eventDispatcher->dispatch($event);
        }

        $errors = $this->getValidator()->validate($household);

        if ($errors->count() > 0) {
            return $this->json($errors, 422);
        }

        $this->managerRegistry->getManager()->flush();

        return $this->json(
            $address,
            Response::HTTP_OK,
            [],
            [AbstractNormalizer::GROUPS => ['read']]
        );
    }

    /**
     * @ParamConverter("household", options={"id": "household_id"})
     */
    #[Route(path: '/api/1.0/person/address/suggest/by-household/{household_id}.{_format}', name: 'chill_person_address_suggest_by_household', requirements: ['_format' => 'json'])]
    public function suggestAddressByHousehold(Household $household, string $_format)
    {
        // TODO add acl

        $addresses = [];
        // collect addresses from location in courses
        foreach ($household->getCurrentPersons() as $person) {
            foreach ($person->getAccompanyingPeriodParticipations() as $participation) {
                if (null !== $participation->getAccompanyingPeriod()->getAddressLocation()) {
                    $a = $participation->getAccompanyingPeriod()->getAddressLocation();
                    $addresses[$a->getId()] = $a;
                }

                if (
                    null !== $personLocation = $participation
                        ->getAccompanyingPeriod()->getPersonLocation()
                ) {
                    $a = $personLocation->getCurrentHouseholdAddress();

                    if (null !== $a) {
                        $addresses[$a->getId()] = $a;
                    }
                }
            }
        }

        // remove the actual address
        $actual = $household->getCurrentAddress();

        if (null !== $actual) {
            $addresses = \array_filter($addresses, static fn ($a) => $a !== $actual);
        }

        return $this->json(
            \array_values($addresses),
            Response::HTTP_OK,
            [],
            ['groups' => ['read']]
        );
    }

    /**
     * Find Household of people participating to the same AccompanyingPeriod.
     *
     * @ParamConverter("person", options={"id": "person_id"})
     */
    public function suggestHouseholdByAccompanyingPeriodParticipationApi(Person $person, string $_format)
    {
        // TODO add acl

        $count = $this->householdRepository->countByAccompanyingPeriodParticipation($person);
        $paginator = $this->getPaginatorFactory()->create($count);

        $households = [];

        if (0 !== $count) {
            $allHouseholds = $this->householdRepository->findByAccompanyingPeriodParticipation(
                $person,
                $paginator->getItemsPerPage(),
                $paginator->getCurrentPageFirstItemNumber()
            );
            $currentHouseholdPerson = $person->getCurrentHousehold();

            foreach ($allHouseholds as $h) {
                if ($h !== $currentHouseholdPerson) {
                    $households[] = $h;
                }
            }

            if (null !== $currentHouseholdPerson) {
                --$count;
                $paginator = $this->getPaginatorFactory()->create($count);
            }
        }
        $collection = new Collection($households, $paginator);

        return $this->json(
            $collection,
            Response::HTTP_OK,
            [],
            ['groups' => ['read']]
        );
    }
}
