<?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\Fragment;

use Ferienpass\CoreBundle\Application\ExtraQuestion;
use Ferienpass\CoreBundle\ConsentManager\ConsentManager;
use Ferienpass\CoreBundle\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\AttendanceExtraFile;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * Renders the confirmation / status page body for a single attendance. Access is
 * decided by the parent {@see \Ferienpass\CmsBundle\Controller\Page\AttendanceShowController};
 * this fragment only reads the entity and presents it.
 */
class AttendanceShowController extends AbstractPrivateFragmentController
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly ConsentManager $consentManager, private readonly UriSigner $uriSigner, #[Autowire(env: 'MAPBOX_TOKEN')] private readonly string $mapboxToken = '')
    {
    }

    public function __invoke(Request $request): Response
    {
        $attendance = $this->attendances->findOneBy(['uuid' => (string) $request->attributes->get('attendance')]);
        if (!$attendance instanceof Attendance) {
            throw $this->createNotFoundException();
        }

        $offer = $attendance->getOffer();
        $participant = $attendance->getParticipant();

        // Consents the offer requires for this participant (account-level + per-
        // participant). Used read-only for the review section, and — when the
        // attendance still awaits them — as the inline signing form.
        $consents = null !== $participant
            ? array_values($this->consentManager->forOfferAndParticipants($offer, [$participant]))
            : [];

        // Whether this attendance is being held for its consents (the minor-with-
        // guardian flow), i.e. the consents section should be an editable signing
        // form rather than a read-only review.
        $needsConsents = null !== $participant && [] !== $consents
            && ($attendance->isAwaitingConsents() || $attendance->isConsentOutstanding());

        // Durable link the applicant can forward to a legal guardian who signs the
        // consents. Points straight at this canonical page carrying the consent
        // token; the old /einwilligung/{token} route only stays as a redirect shim
        // for links shared before the move, so a freshly generated one skips it.
        $shareUrl = null;
        if ($needsConsents && null !== $attendance->getConsentToken()) {
            $shareUrl = $this->generateUrl('cms_attendance_show', [
                'attendance' => $attendance->getUuid()->toBase58(),
                'token' => $attendance->getConsentToken(),
            ], UrlGeneratorInterface::ABSOLUTE_URL);
        }

        return $this->render('@Contao/fragment/attendance_show.html.twig', [
            'attendance' => $attendance,
            'offer' => $offer,
            'participant' => $participant,
            'access' => 'anon' === $request->attributes->get('access') ? 'anon' : 'auth',
            'formAction' => (string) $request->attributes->get('formAction'),
            'consentError' => $request->attributes->get('consentError'),
            'answersError' => $request->attributes->get('answersError'),
            'consents' => $consents,
            'needsConsents' => $needsConsents,
            'shareUrl' => $shareUrl,
            'questions' => $this->questions($attendance, 'anon' === $request->attributes->get('access')),
            // Corrections stay possible while the application can still lead
            // somewhere. A refused one (rejected / no spot) is history: the answers
            // are shown for the record, but changing them would only look like it
            // still mattered. Withdrawn ones do not reach this section at all.
            'answersEditable' => !$attendance->isWithdrawn() && !$attendance->isRejected() && !$attendance->isUnfulfilled(),
            'isCreatedByAdmin' => $attendance->isCreatedByAdmin(),
            'mapboxToken' => $this->mapboxToken,
        ]);
    }

    /**
     * The offer's extra application questions paired with this attendance's stored
     * answers, ready to be reviewed AND corrected. Definitions live on the offer
     * ({@see \Ferienpass\CoreBundle\Entity\Offer\OfferInterface::getApplicationExtra()}),
     * answers on {@see Attendance::getExtra()} keyed by the question uuid; a `file`
     * answer additionally carries its {@see AttendanceExtraFile} and the URL to
     * view/download it.
     *
     * @param bool $anon whether the viewer got here without an account — their file
     *                   links need a signature of their own
     *
     * @return list<array{uuid: string, question: string, type: string, required: bool, fileTypes: list<string>, answer: string|bool|int|null, file: AttendanceExtraFile|null, fileUrl: string|null}>
     */
    private function questions(Attendance $attendance, bool $anon): array
    {
        $questions = [];
        foreach ($attendance->getOffer()->getApplicationExtra() ?? [] as $extra) {
            if ('' === trim((string) ($extra['question'] ?? ''))) {
                continue;
            }

            $uuid = (string) ($extra['uuid'] ?? '');
            $type = ExtraQuestion::type($extra['type'] ?? null);
            $file = ExtraQuestion::TYPE_FILE === $type ? $attendance->getExtraFile($uuid) : null;

            $questions[] = [
                'uuid' => $uuid,
                'question' => (string) $extra['question'],
                'type' => $type,
                'required' => (bool) ($extra['required'] ?? false),
                'fileTypes' => ExtraQuestion::TYPE_FILE === $type ? ExtraQuestion::kinds($extra['fileTypes'] ?? null) : [],
                'answer' => $attendance->getExtra($uuid),
                'file' => $file,
                'fileUrl' => $file instanceof AttendanceExtraFile ? $this->fileUrl($attendance, $uuid, $anon) : null,
            ];
        }

        return $questions;
    }

    /**
     * The link to one uploaded file. A UriSigner signature covers the whole URI, so
     * the signature that let an anonymous visitor onto the page does not carry over
     * to the file path — sign a short-lived one for it instead.
     */
    private function fileUrl(Attendance $attendance, string $question, bool $anon): string
    {
        $parameters = [
            'attendance' => $attendance->getUuid()->toBase58(),
            'question' => ExtraQuestion::urlId($question),
        ];

        if (!$anon) {
            return $this->generateUrl('cms_attendance_file', $parameters);
        }

        $parameters['valid'] = new \DateTimeImmutable('+1 day')->format('c');

        return $this->uriSigner->sign(
            $this->generateUrl('cms_attendance_file', $parameters, UrlGeneratorInterface::ABSOLUTE_URL)
        );
    }
}
