<?php

namespace PloverCRM\Modules\Automations\Actions;

use PloverCRM\Modules\Automations\Services\InternalEmailRenderer;

/**
 * Sends an internal email for an automation run.
 */
class SendInternalEmailAction
{
    public function execute(array $config, array $payload): array
    {
        $contact = $payload['contact'] ?? [];
        $recipients = array_values(array_unique(array_filter((array) ($config['to'] ?? []), function ($email) {
            return is_email($email);
        })));

        if (empty($recipients)) {
            throw new \RuntimeException('No valid recipient emails were provided.');
        }

        $rendered = InternalEmailRenderer::render($config, $contact);
        $subject = $rendered['subject'];
        $body = $rendered['body'];
        $headers = InternalEmailRenderer::buildHeaders();

        $sent = [];
        $failed = [];

        foreach ($recipients as $recipient) {
            $result = wp_mail($recipient, $subject, $body, $headers);

            if ($result) {
                $sent[] = $recipient;
            } else {
                $failed[] = $recipient;
            }
        }

        return [
            'type' => 'send_internal_email',
            'subject' => $subject,
            'recipients_sent' => $sent,
            'recipients_failed' => $failed,
        ];
    }
}
