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

use Ferienpass\CoreBundle\ConsentManager\ConsentManager;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\UX\Turbo\TurboBundle;

/**
 * Signs the per-season host confidentiality declaration
 * ({@see Edition::getHostConsentForm()}). Replaces the former app-wide
 * `/datenschutz-einwilligung` page: the declaration is presented in context
 * (the participant-list gate, see missing_privacy_statement.html.twig) and this
 * endpoint records the signature as a {@see \Ferienpass\CoreBundle\Entity\Consent}
 * via the {@see ConsentManager}, then answers with a Turbo Stream that swaps the
 * gate for an "unlocked" panel — no flash, no redirect.
 */
final class HostConsentController extends AbstractController
{
    #[Route('/saisons/{alias}/veranstalter-einverstaendnis/zeichnen', name: 'admin_host_consent_sign', methods: ['POST'])]
    public function sign(#[MapEntity(mapping: ['alias' => 'alias'])] Edition $edition, #[CurrentUser] User $user, Request $request, ConsentManager $consentManager): Response
    {
        $hostForm = $edition->getHostConsentForm();
        if (null === $hostForm || !$edition->isHostAgreementActive()) {
            throw $this->createNotFoundException();
        }

        if (!$this->isCsrfTokenValid('host_consent', (string) $request->request->get('_token'))) {
            throw $this->createAccessDeniedException('Invalid CSRF token.');
        }

        $returnUrl = $this->returnUrl($request, $edition);
        $isStream = TurboBundle::STREAM_FORMAT === $request->getPreferredFormat();

        // Guard against a submit without ticking the box (no-JS / tampering).
        if (!$request->request->getBoolean('accept')) {
            if ($isStream) {
                $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

                return $this->renderBlock('@FerienpassAdmin/page/missing_privacy_statement.html.twig', 'not_accepted_stream', []);
            }

            return $this->redirect($returnUrl);
        }

        // Idempotent: ConsentManager reuses an existing valid signature.
        $consentManager->sign($hostForm, $user);

        if ($isStream) {
            $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

            return $this->renderBlock('@FerienpassAdmin/page/missing_privacy_statement.html.twig', 'signed_stream', [
                'returnUrl' => $returnUrl,
            ]);
        }

        return $this->redirect($returnUrl);
    }

    /**
     * The posted return target, restricted to a local path to avoid an open
     * redirect; falls back to the edition's offer list.
     */
    private function returnUrl(Request $request, Edition $edition): string
    {
        $return = (string) $request->request->get('return', '');
        if (str_starts_with($return, '/') && !str_starts_with($return, '//')) {
            return $return;
        }

        return $this->generateUrl('admin_offers_index', ['edition' => $edition->getAlias()]);
    }
}
