<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Marketing;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Behavior\HasTemplateOverride;
use CpCreation\VitiCore\Marketing\Model\ReviewInvitation;
use CpCreation\VitiCore\Marketing\Model\ReviewSolicitationOptOut as ReviewSolicitationOptOutModel;
use CpCreation\VitiCore\Marketing\Repository\ReviewInvitationRepository;
use CpCreation\VitiCore\Marketing\Repository\ReviewSolicitationOptOutRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('marketing:ReviewSolicitationOptOut', template: '@components/marketing/ReviewSolicitationOptOut.html.twig')]
final class ReviewSolicitationOptOut
{
    use DefaultActionTrait;
    use HasTemplateOverride;

    #[LiveProp]
    public string $token = '';

    #[LiveProp]
    public bool $saved = false;

    private ?ReviewInvitation $invitation = null;

    public function __construct(
        private readonly ReviewInvitationRepository $invitationRepository,
        private readonly ReviewSolicitationOptOutRepository $optOutRepository,
    ) {}

    public function isAlreadyOptedOut(): bool
    {
        return $this->optOutRepository->hasOptedOut($this->resolveInvitation()->getRecipientEmail());
    }

    #[LiveAction]
    public function confirmOptOut(): void
    {
        $invitation = $this->resolveInvitation();

        if (!$this->optOutRepository->hasOptedOut($invitation->getRecipientEmail())) {
            $this->optOutRepository->persist(new ReviewSolicitationOptOutModel(
                $invitation->getRecipientEmail(),
                $invitation,
            ));
        }

        $invitation->suppressReminder();
        $this->invitationRepository->persist($invitation);
        $this->optOutRepository->flush();
        $this->saved = true;
    }

    private function resolveInvitation(): ReviewInvitation
    {
        if ($this->invitation instanceof ReviewInvitation) {
            return $this->invitation;
        }

        $invitation = $this->invitationRepository->findOneByToken($this->token);
        if (!$invitation instanceof ReviewInvitation) {
            throw new NotFoundHttpException();
        }

        return $this->invitation = $invitation;
    }
}
