<?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 Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CmsBundle\Controller\AbstractController;
use Ferienpass\CmsBundle\Fragment\FragmentReference;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Enum\AttendanceTransition;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
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\Uid\Uuid;
use Symfony\Component\Workflow\WorkflowInterface;

/**
 * Performs an unauthenticated withdrawal after the visitor clicks the signed link
 * from the confirmation e-mail. Modelled on the magic-link flow: a GET renders an
 * interstitial that immediately POSTs the (still signed) URL back, so an inbox
 * scanner's prefetch — always a GET — cannot trigger the irreversible withdrawal.
 */
class AttendanceWithdrawConfirmController extends AbstractController
{
    public function __construct(
        private readonly UriSigner $uriSigner,
        private readonly WorkflowInterface $attendanceStateMachine,
        private readonly EntityManagerInterface $entityManager,
        private readonly AttendanceRepository $attendances,
    ) {
    }

    #[Route('/abmeldung-bestaetigen/{attendance}', name: 'cms_attendance_withdraw_confirm', requirements: ['attendance' => '[1-9A-HJ-NP-Za-km-z]+'], methods: ['GET', 'POST'])]
    public function __invoke(string $attendance, Request $request): Response
    {
        $this->initializeContaoFramework();

        $attendance = $this->findByBase58($attendance);

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

        // Idempotent: a second click (or the browser retrying) after the withdrawal
        // already happened just lands back on the status page.
        if ($attendance->isWithdrawn()) {
            return $this->redirectToConfirmationPage($attendance);
        }

        if ($request->isMethod('POST')) {
            // CSRF is enforced globally by Contao's RequestTokenListener (frontend
            // scope, REQUEST_TOKEN in the interstitial form).
            $this->withdraw($attendance);

            return $this->redirectToConfirmationPage($attendance);
        }

        return $this->markPageAsPrivate(
            $this->createPageBuilder()
                ->addFragment('main', new FragmentReference('ferienpass.fragment.attendance_withdraw_confirm', [
                    'attendance' => $attendance->getUuid()->toRfc4122(),
                    'formAction' => $request->getRequestUri(),
                ]))
                ->getResponse()
        );
    }

    private function withdraw(Attendance $attendance): void
    {
        // The guard (deadline / grace period / already-started / cancelled) still
        // applies to the anonymous visitor — exactly as it does in the account flow.
        if (!$this->attendanceStateMachine->can($attendance, AttendanceTransition::WITHDRAW)) {
            return;
        }

        // Always transition to WITHDRAWN (never hard-delete as the lottery flow in
        // "Meine Anmeldungen" does): the record must survive so this anonymous
        // visitor is redirected to a confirmation page instead of a 404, and the
        // freed slot is handled by the WITHDRAWN transition's reorder either way.
        $this->attendanceStateMachine->apply($attendance, AttendanceTransition::WITHDRAW, ['notify' => false]);
        $this->entityManager->flush();
    }

    private function redirectToConfirmationPage(Attendance $attendance): Response
    {
        // The visitor is anonymous; grant continued access to the (now withdrawn)
        // 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)
        ), Response::HTTP_SEE_OTHER);
    }

    private function findByBase58(string $base58): Attendance
    {
        try {
            $uuid = Uuid::fromBase58($base58);
        } catch (\InvalidArgumentException) {
            throw new PageNotFoundException();
        }

        $attendance = $this->attendances->findOneBy(['uuid' => $uuid]);
        if (!$attendance instanceof Attendance) {
            throw new PageNotFoundException();
        }

        return $attendance;
    }

    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;
        }
    }
}
