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

use Chill\TicketBundle\Action\Ticket\AddAddresseeCommand;
use Chill\TicketBundle\Action\Ticket\Handler\SetAddresseesCommandHandler;
use Chill\TicketBundle\Action\Ticket\SetAddresseesCommand;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final readonly class SetAddresseesController
{
    public function __construct(
        private Security $security,
        private EntityManagerInterface $entityManager,
        private SerializerInterface $serializer,
        private SetAddresseesCommandHandler $addressesCommandHandler,
        private ValidatorInterface $validator,
    ) {}

    #[Route('/api/1.0/ticket/{id}/addressees/set', methods: ['POST'])]
    public function setAddressees(Ticket $ticket, Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users can set addressees.');
        }

        $command = $this->serializer->deserialize($request->getContent(), SetAddresseesCommand::class, 'json', [AbstractNormalizer::GROUPS => ['read']]);

        return $this->registerSetAddressees($command, $ticket);
    }

    #[Route('/api/1.0/ticket/{id}/addressee/add', methods: ['POST'])]
    public function addAddressee(Ticket $ticket, Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users can add addressees.');
        }

        $command = $this->serializer->deserialize($request->getContent(), AddAddresseeCommand::class, 'json', [AbstractNormalizer::GROUPS => ['read']]);

        return $this->registerSetAddressees(SetAddresseesCommand::fromAddAddresseeCommand($command, $ticket), $ticket);
    }

    private function registerSetAddressees(SetAddresseesCommand $command, Ticket $ticket): Response
    {
        if (0 < count($errors = $this->validator->validate($command))) {
            return new JsonResponse(
                $this->serializer->serialize($errors, 'json'),
                Response::HTTP_UNPROCESSABLE_ENTITY,
                [],
                true
            );
        }

        $this->addressesCommandHandler->handle($ticket, $command);

        $this->entityManager->flush();

        return new JsonResponse(
            $this->serializer->serialize($ticket, 'json', ['groups' => 'read']),
            Response::HTTP_OK,
            [],
            true,
        );
    }
}
