<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Marketing\Model\ReviewInvitation;
use CpCreation\VitiCore\Marketing\Repository\ReviewInvitationRepository;
use CpCreation\VitiCore\Marketing\Repository\ReviewRequestConfigurationRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

final class ProductReviewController extends AbstractController
{
    public function __construct(
        private readonly ReviewInvitationRepository $invitationRepository,
        private readonly ReviewRequestConfigurationRepository $configurationRepository,
    ) {}

    public function invitation(string $token): Response
    {
        $configuration = $this->configurationRepository->findOne();
        $invitation = $this->invitationRepository->findOneByToken($token);

        if (
            null === $configuration
            || !$configuration->isEnabled()
            || !$invitation instanceof ReviewInvitation
            || !$invitation->isUsableAt(new \DateTimeImmutable())
        ) {
            throw $this->createNotFoundException();
        }

        return $this->protectTokenResponse($this->render('marketing/review/invitation.html.twig', [
            'token' => $token,
        ]));
    }

    private function protectTokenResponse(Response $response): Response
    {
        $response->headers->set('X-Robots-Tag', 'noindex, nofollow, noarchive');
        $response->headers->set('Referrer-Policy', 'no-referrer');
        $response->headers->set('Cache-Control', 'private, no-store');

        return $response;
    }
}
