<?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\OfferFinalized as OfferFinalizedEvent;
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;

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

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

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

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