<?php

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

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\ActionType;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\SendEmailAction;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionInfo\ExecutionInfo;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionInfo\SendEmailInfo;
use idoit\Module\SyneticsFlows\Automation\Automation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;
use idoit\Module\SyneticsFlows\Template\TemplateFactory;

class SendEmailFactory implements ExecutionFactory
{
    public function __construct(private TemplateFactory $factory)
    {
    }

    /**
     * @param Invocation $invocation
     * @param Automation $automation
     * @param ActionType $actionType
     *
     * @return ExecutionInfo|null
     */
    public function createExecution(Invocation $invocation, Automation $automation, ActionType $actionType): ?ExecutionInfo
    {
        if (!$actionType instanceof SendEmailAction){
            return null;
        }
        $template = $this->factory->forInvocation($invocation, $automation);

        $body = $template->process($actionType->getBody());
        $subject = $template->process($actionType->getSubject());
        $recipients = $actionType->getRecipientsList();

        if (empty($recipients)) {
            return null;
        }

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

    /**
     * @param ActionType $actionType
     *
     * @return bool
     */
    public function supports(ActionType $actionType): bool
    {
        return $actionType instanceof SendEmailAction;
    }
}
