<?php
namespace WooNooW\Core\Mail;

/**
 * Intercepts wp_mail() calls and queues them asynchronously via Action Scheduler.
 * This prevents blocking operations (SMTP, DNS lookups) from slowing down API responses.
 */
class WooEmailOverride {
    private static $enabled = true;

    public static function init() {
        // Hook into wp_mail before it's sent
        add_filter('pre_wp_mail', [__CLASS__, 'interceptMail'], 10, 2);
    }

    /**
     * Intercept wp_mail() and queue it asynchronously.
     * Return non-null to short-circuit wp_mail().
     */
    public static function interceptMail($null, $atts) {
        if (!self::$enabled) {
            return $null; // Allow normal wp_mail if disabled
        }

        // Queue the email asynchronously
        MailQueue::enqueue([
            'to'          => $atts['to'] ?? '',
            'subject'     => $atts['subject'] ?? '',
            'html'        => $atts['message'] ?? '',
            'headers'     => $atts['headers'] ?? [],
            'attachments' => $atts['attachments'] ?? [],
        ]);

        // Return true to indicate success and prevent wp_mail from running
        return true;
    }

    /**
     * Temporarily disable async mail (for testing or critical emails).
     */
    public static function disable() {
        self::$enabled = false;
    }

    /**
     * Re-enable async mail.
     */
    public static function enable() {
        self::$enabled = true;
    }
}