<?php

namespace Modules\Workflows\Services\Actions;

use Gestoreasy\Core\Mail\Mailer;

class SendEmailAction implements ActionInterface {
    private string $tenantId;

    public function __construct(string $tenantId) {
        $this->tenantId = $tenantId;
    }

    public function execute(array $config, array $context): array {
        $to = $this->resolveVariable($config['to'] ?? '', $context);
        $subject = $this->resolveVariable($config['subject'] ?? '', $context);
        $body = $this->resolveVariable($config['body'] ?? '', $context);
        $from = $config['from'] ?? null;

        if (!$to) {
            throw new \Exception('Email destination is required');
        }

        $mailer = new Mailer();
        $mailer->send($to, $subject, $body, $from);

        return [
            'sent' => true,
            'to' => $to,
            'subject' => $subject
        ];
    }

    /**
     * Resolve variáveis no formato {{variable}}
     */
    private function resolveVariable(string $value, array $context): string {
        return preg_replace_callback('/\{\{([^}]+)\}\}/', function($matches) use ($context) {
            $var = trim($matches[1]);
            $parts = explode('.', $var);
            $result = $context;

            foreach ($parts as $part) {
                if (isset($result[$part])) {
                    $result = $result[$part];
                } else {
                    return $matches[0]; // Retorna original se não encontrar
                }
            }

            return is_scalar($result) ? (string)$result : $matches[0];
        }, $value);
    }
}

