<?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 Ferienpass\CmsBundle\Controller\AbstractController;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

/**
 * Backward-compatible shim for the former consent-signing page. The consent
 * signing now lives on the canonical confirmation page
 * ({@see AttendanceShowController}); this route only resolves the token to its
 * attendance and forwards there, so links already e-mailed or copied by an admin
 * (which point at /einwilligung/{token}) keep working. The token travels on to the
 * confirmation page, where it grants access to sign the outstanding consents.
 */
class ConsentLinkController extends AbstractController
{
    #[Route('/einwilligung/{token}', name: 'cms_consent_link', methods: ['GET'])]
    public function __invoke(string $token, AttendanceRepository $attendanceRepository): Response
    {
        $this->initializeContaoFramework();

        $attendance = $attendanceRepository->findOneBy(['consentToken' => $token]);
        if (!$attendance instanceof Attendance) {
            throw $this->createNotFoundException();
        }

        // 302 (not 301): the confirmation page it forwards to is per-attendance and
        // private; a permanently-cached redirect could outlive the token's meaning.
        return $this->redirectToRoute('cms_attendance_show', [
            'attendance' => $attendance->getUuid()->toBase58(),
            'token' => $token,
        ], Response::HTTP_FOUND);
    }
}
