<?php

namespace idoit\Module\SyneticsFlows\Automation\Action\PerformExecution;

use idoit\Module\SyneticsFlows\Automation\Action\ExecutionInfo\SendEmailInfo;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ErrorExecutionResult;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ExecutionResult;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\SendEmailResult;
use idoit\Module\SyneticsFlows\Automation\Execution;
use idoit\Module\SyneticsFlows\Mailer\FlowMailer;
use Throwable;

class SendEmailExecution implements PerformExecution
{
    /**
     * @param Execution $execution
     *
     * @return ExecutionResult
     */
    public function perform(Execution $execution): ExecutionResult
    {
        $parameters = $execution->getExecution();
        if (!$parameters instanceof SendEmailInfo) {
            return new ErrorExecutionResult('Unsupported execution');
        }
        $subject = $parameters->getSubject();
        $body = $parameters->getBody() ?? '';
        $recipients = $parameters->getRecipient();

        try {
            if (empty($recipients)) {
                return new ErrorExecutionResult('No recipients defined');
            }

            $mailer = new FlowMailer();

            $mailer->set_charset('UTF-8');
            $mailer->set_content_type(FlowMailer::C__CONTENT_TYPE__PLAIN);
            $mailer->set_backend(FlowMailer::C__BACKEND__SMTP);
            $mailer->set_subject($subject);
            $mailer->set_body($body);

            foreach ($recipients as $recipient) {
                $mailer->addAddress($recipient);
                $mailer->send();
                $mailer->clearAddresses();
            }
        } catch (Throwable $e) {
            return new ErrorExecutionResult($e->getMessage());
        }

        return new SendEmailResult($subject, $body, $recipients);
    }

    /**
     * @param Execution $execution
     *
     * @return bool
     */
    public function supports(Execution $execution): bool
    {
        return $execution->getExecution() instanceof SendEmailInfo;
    }
}
