<?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\Payment;
use Ferienpass\CoreBundle\Message\PaymentReceiptCreated as PaymentReceiptCreatedEvent;
use Ferienpass\CoreBundle\Notification\PaymentCreatedNotification;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\RuntimeException;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'event.bus')]
class PaymentReceiptCreated
{
    public function __construct(private readonly Notifier $notifier, private readonly PaymentRepository $payments)
    {
    }

    public function __invoke(PaymentReceiptCreatedEvent $event, Uuid $uuid): void
    {
        if (!$event->shouldNotify()) {
            return;
        }

        /** @var Payment $payment */
        $payment = $this->payments->findOneBy(['uuid' => $event->getPaymentUuid()]);
        if (null === $payment) {
            throw new RuntimeException("Payment uuid {$event->getPaymentUuid()} not found. Maybe not flushed yet?");
        }

        $notification = $this->notifier->paymentCreated($payment);
        if (!$notification instanceof PaymentCreatedNotification) {
            return;
        }

        $this->notifier->send($notification->belongsTo($uuid), new Recipient((string) $payment->getBillingEmail()));
    }
}
