<?php
declare(strict_types=1);

namespace Autogedal\BlackFriday\Controller\Adminhtml\Subscriber;

use Autogedal\BlackFriday\Model\LaunchMailer;
use Autogedal\BlackFriday\Model\SubscriberStorage;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Validator\EmailAddress;
use Magento\Store\Model\StoreManagerInterface;

/** Sends the launch email to an address, with the favourites of a chosen subscriber. Does not change any status. */
class SendTest extends Action implements HttpPostActionInterface
{
    public const ADMIN_RESOURCE = 'Autogedal_BlackFriday::subscribers';

    public function __construct(
        Context $context,
        private readonly LaunchMailer $mailer,
        private readonly SubscriberStorage $storage,
        private readonly StoreManagerInterface $storeManager,
        private readonly EmailAddress $emailValidator
    ) {
        parent::__construct($context);
    }

    public function execute()
    {
        $recipient = trim((string)$this->getRequest()->getParam('recipient'));
        $source = trim((string)$this->getRequest()->getParam('subscriber'));
        $redirect = $this->resultRedirectFactory->create()->setPath('*/*/testEmail');
        if (!$this->emailValidator->isValid($recipient)) {
            $this->messageManager->addErrorMessage(__('Adresa de email pentru test nu este valida.'));
            return $redirect;
        }
        $row = $source !== '' ? $this->storage->get($source) : null;
        if (!$row) {
            $this->messageManager->addErrorMessage(__('Alege un abonat cu produse favorite.'));
            return $redirect;
        }
        try {
            $storeId = (int)$row['store_id'] ?: (int)$this->storeManager->getDefaultStoreView()->getId();
            $this->mailer->send($recipient, array_filter(explode(',', (string)$row['favorites'])), $storeId);
            $this->messageManager->addSuccessMessage(__('Emailul de test a fost trimis la %1, cu favoritele lui %2.', $recipient, $row['email']));
        } catch (\Throwable $e) {
            $this->messageManager->addErrorMessage(__('Emailul de test nu a putut fi trimis: %1', $e->getMessage()));
        }
        return $redirect;
    }
}
