<?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\Attendance;
use Ferienpass\CoreBundle\Message\AnonymousAttendanceUnconfirmed as AnonymousAttendanceUnconfirmedEvent;
use Ferienpass\CoreBundle\Notification\AttendanceEmailConfirmationNotification;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\HttpFoundation\UriSigner;
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 AnonymousAttendanceUnconfirmed
{
    public function __construct(private readonly Notifier $notifier, private readonly AttendanceRepository $attendances, private readonly UrlGeneratorInterface $urlGenerator, private readonly UriSigner $uriSigner, private readonly AttendanceEmailConfirmationNotification $defaultNotification, private readonly TranslatorInterface $translator)
    {
    }

    public function __invoke(AnonymousAttendanceUnconfirmedEvent $event, Uuid $uuid): void
    {
        $attendance = $this->attendances->findOneBy(['uuid' => $event->getAttendance()]);
        if (!$attendance instanceof Attendance || !$attendance->isEmailUnconfirmed()) {
            return;
        }

        $email = (string) $attendance->getParticipant()?->getEmail();
        if ('' === $email) {
            return;
        }

        // Prefer a DB-configured notification; otherwise fall back to the built-in
        // default content so the confirmation always sends (like the login-link mail).
        $notification = $this->notifier->attendanceEmailConfirmation($attendance);
        if (!$notification instanceof AttendanceEmailConfirmationNotification) {
            $notification = (clone $this->defaultNotification)
                ->attendance($attendance)
                ->subject($this->translator->trans('defaults.attendance_email_confirmation.emailSubject', [], 'notifications'))
                ->content($this->translator->trans('defaults.attendance_email_confirmation.emailText', [], 'notifications'))
            ;
        }

        // The confirmation URL is signed, so it must be built from the
        // canonical base host (router default_uri / APP_BASE_URL), never from a
        // per-request, attacker-controllable Host header. We deliberately do
        // NOT apply any host carried on the event; the UrlGenerator's configured
        // default request context provides the trusted absolute base.
        $actionUrl = $this->uriSigner->sign(
            $this->urlGenerator->generate('cms_attendance_confirm', [
                'uuid' => $attendance->getUuid(),
                'valid' => new \DateTimeImmutable('+14 days')->format('c'),
            ], UrlGeneratorInterface::ABSOLUTE_URL)
        );

        $this->notifier->send(
            $notification->belongsTo($uuid)->actionUrl($actionUrl),
            new Recipient($email)
        );
    }
}
