<?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\Enum\AttendanceTransition;
use Ferienpass\CoreBundle\Message\AttendanceWithdrawRequested as AttendanceWithdrawRequestedEvent;
use Ferienpass\CoreBundle\Notification\AttendanceWithdrawConfirmationNotification;
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\Component\Workflow\WorkflowInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Sends the e-mail whose signed link lets an unauthenticated visitor confirm the
 * withdrawal they requested on the confirmation page. Mirrors the anonymous
 * e-mail-confirmation flow ({@see AnonymousAttendanceUnconfirmed}).
 */
#[AsMessageHandler(bus: 'event.bus')]
class AttendanceWithdrawRequested
{
    public function __construct(private readonly Notifier $notifier, private readonly AttendanceRepository $attendances, private readonly UrlGeneratorInterface $urlGenerator, private readonly UriSigner $uriSigner, private readonly WorkflowInterface $attendanceStateMachine, private readonly AttendanceWithdrawConfirmationNotification $defaultNotification, private readonly TranslatorInterface $translator)
    {
    }

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

        // Only offer the confirmation when the withdrawal is actually permitted
        // (deadline / grace period / already-started guards); no point mailing a
        // link that would be refused on click.
        if (!$this->attendanceStateMachine->can($attendance, AttendanceTransition::WITHDRAW)) {
            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->attendanceWithdrawConfirmation($attendance);
        if (!$notification instanceof AttendanceWithdrawConfirmationNotification) {
            $notification = (clone $this->defaultNotification)
                ->attendance($attendance)
                ->subject($this->translator->trans('defaults.attendance_withdraw_confirmation.emailSubject', [], 'notifications'))
                ->content($this->translator->trans('defaults.attendance_withdraw_confirmation.emailText', [], 'notifications'))
            ;
        }

        // The withdraw URL is signed, so — as for the e-mail confirmation link — it
        // is built from the current (trusted-hosts filtered) request context, never
        // from an attacker-controllable Host. The handler runs synchronously in the
        // frontend request that initiated the withdrawal, so that context is correct.
        $actionUrl = $this->uriSigner->sign(
            $this->urlGenerator->generate('cms_attendance_withdraw_confirm', [
                'attendance' => $attendance->getUuid()->toBase58(),
                'valid' => new \DateTimeImmutable('+24 hours')->format('c'),
            ], UrlGeneratorInterface::ABSOLUTE_URL)
        );

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