<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\NotificationHandler;

use Ferienpass\CoreBundle\Entity\Offer\Base;
use Ferienpass\CoreBundle\Message\OfferCompleted as OfferCompletedEvent;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\Translation\TranslatorInterface;

#[AsMessageHandler(bus: 'event.bus')]
class OfferCompleted
{
    public function __construct(private readonly Notifier $notifier, private readonly OfferRepositoryInterface $offers, private readonly UrlGeneratorInterface $urlGenerator, private readonly TranslatorInterface $translator)
    {
    }

    public function __invoke(OfferCompletedEvent $event, Uuid $uuid): void
    {
        /** @var Base $offer */
        $offer = $this->offers->findOneBy(['uuid' => $event->getOfferId()]);
        if (null === $offer) {
            return;
        }

        $notification = $this->notifier->offerCompleted($offer);
        if (!$notification instanceof \Ferienpass\CoreBundle\Notification\OfferCompletedNotification || '' === $email = (string) $notification->getEmailTo()) {
            return;
        }

        $templateData = [];

        // TODO use normalizer and serializer groups
        foreach ($event->getSurveyData() as $k => $v) {
            if (\is_scalar($v)) {
                $key = $this->translator->trans('surveys.feedback.label.'.$k);
                $templateData[$key] = $v;
            }
        }

        $this->notifier->send(
            $notification
                ->belongsTo($uuid)
                ->surveyData($templateData)
                ->actionUrl($this->urlGenerator->generate('admin_offers_complete', ['uuid' => $offer->getUuid()->toBase58()], UrlGeneratorInterface::ABSOLUTE_URL)),
            new Recipient($email)
        );
    }
}
