<?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\CmsBundle\Controller\Page;

use Contao\CoreBundle\Exception\PageNotFoundException;
use Ferienpass\CmsBundle\Controller\AbstractController;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Facade\AttendanceFacade;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Requirement\Requirement;

/**
 * Confirms an anonymous (no-account) application via the signed link from the
 * confirmation e-mail, releasing the held attendance into the normal allocation,
 * then forwards to the canonical confirmation page {@see AttendanceShowController}.
 */
class AttendanceConfirmController extends AbstractController
{
    public function __construct(private readonly UriSigner $uriSigner, private readonly AttendanceFacade $attendanceFacade)
    {
    }

    #[Route('/anmeldung-bestaetigen/{uuid}', name: 'cms_attendance_confirm', requirements: ['uuid' => Requirement::UUID])]
    public function __invoke(#[MapEntity(mapping: ['uuid' => 'uuid'])] Attendance $attendance, Request $request): Response
    {
        $this->initializeContaoFramework();

        if (!$this->isValidLink($request)) {
            throw new PageNotFoundException();
        }

        // Idempotent: mail clients/scanners prefetch links. confirmEmail() only
        // acts while the attendance is still held, so a second visit is harmless.
        $this->attendanceFacade->confirmEmail($attendance);

        // The visitor is anonymous (no account), so grant them continued access to
        // the status page with a freshly signed URL of its own.
        return $this->redirect($this->uriSigner->sign(
            $this->generateUrl('cms_attendance_show', [
                'attendance' => $attendance->getUuid()->toBase58(),
                'valid' => new \DateTimeImmutable('+14 days')->format('c'),
            ], UrlGeneratorInterface::ABSOLUTE_URL)
        ));
    }

    private function isValidLink(Request $request): bool
    {
        if (!$this->uriSigner->checkRequest($request)) {
            return false;
        }

        $valid = $request->query->get('valid');
        if (!\is_string($valid) || '' === $valid) {
            return false;
        }

        try {
            return new \DateTimeImmutable($valid) >= new \DateTimeImmutable();
        } catch (\DateMalformedStringException) {
            return false;
        }
    }
}
