<?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\AssociateByPhonenumberCommand;
use Chill\TicketBundle\Action\Ticket\Handler\AssociateByPhonenumberCommandHandler;
use Chill\TicketBundle\Action\Ticket\CreateTicketCommand;
use Chill\TicketBundle\Action\Ticket\Handler\CreateTicketCommandHandler;
use Chill\TicketBundle\Repository\TicketRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
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\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;

final readonly class CreateTicketController
{
    public function __construct(
        private CreateTicketCommandHandler $createTicketCommandHandler,
        private AssociateByPhonenumberCommandHandler $associateByPhonenumberCommandHandler,
        private Security $security,
        private UrlGeneratorInterface $urlGenerator,
        private EntityManagerInterface $entityManager,
        private TicketRepositoryInterface $ticketRepository,
    ) {}

    #[Route('{_locale}/ticket/ticket/create')]
    public function __invoke(Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users are allowed to create tickets.');
        }

        if ('' !== $extId = $request->query->get('extId', '')) {
            if (null !== $ticket = $this->ticketRepository->findOneByExternalRef($extId)) {
                return new RedirectResponse(
                    $this->urlGenerator->generate('chill_ticket_ticket_edit', ['id' => $ticket->getId()])
                );
            }
        }

        $createCommand = new CreateTicketCommand($request->query->get('extId', ''));
        $ticket = $this->createTicketCommandHandler->__invoke($createCommand);

        $this->entityManager->persist($ticket);

        if ($request->query->has('caller')) {
            $associateByPhonenumberCommand = new AssociateByPhonenumberCommand($request->query->get('caller'));
            $this->associateByPhonenumberCommandHandler->__invoke($ticket, $associateByPhonenumberCommand);
        }

        $this->entityManager->flush();

        $query = [];
        if ($request->query->has('returnPath')) {
            $query['returnPath'] = $request->query->get('returnPath');
        }

        return new RedirectResponse(
            $this->urlGenerator->generate('chill_ticket_ticket_edit', ['id' => $ticket->getId(), ...$query])
        );
    }
}
