<?php
declare(strict_types=1);

namespace App\State\Processor;

use AltchaOrg\Altcha\Altcha;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResource\ContactRequest;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

class ContactRequestProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly MailerInterface $symfonyMailer,
        private readonly string $fromEmail,
        private readonly string $contactEmail,
        private readonly string $contactEmailSauvagerie,
        private readonly string $hmacKey,
        private readonly RequestStack $requestStack
    )
    {}

    /**
     * @throws TransportExceptionInterface
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ContactRequest
    {
        if (!$operation instanceof Post) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        /** @var ContactRequest $contactRequest */
        $contactRequest = $data;

        try {
            $valid = Altcha::verifySolution(
                $contactRequest->getAltchaPayload(),
                $this->hmacKey,
                true
            );
        } catch (\Throwable) {
            $valid = false;
        }

        if (!$valid) {
            throw new \RuntimeException('Invalid payload');
        }

        // Get the recipient parameter from the query, default to 'cv' if not provided
        $request = $this->requestStack->getCurrentRequest();
        $recipient = $request ? $request->query->get('recipient', 'cv') : 'cv';

        // Determine the email recipient based on the recipient parameter
        $emailTo = $recipient === 'sauvagerie' ? $this->contactEmailSauvagerie : $this->contactEmail;

        $symfonyMail = (new Email())
            ->to($emailTo)
            ->from($this->fromEmail)
            ->subject('Contact from ' . $recipient . ' website')
            ->text(
                'From : ' . $contactRequest->getEmail() . "\n" .
                'Name: ' . ($contactRequest->getName() ?? '-') . "\n\n" .
                $contactRequest->getMessage()
            );

        $this->symfonyMailer->send($symfonyMail);

        return $contactRequest;
    }
}
