<?php

namespace App\Mail\Concerns;

use App\Models\MailingBounce;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Mime\Email;

trait TracksBounces
{
    /**
     * Configure bounce tracking headers for this mailable
     */
    protected function configureBounceTracking($message)
    {
        $bounceEmail = timebank_config('mailing.bounce_address', config('mail.from.address'));

        $message->withSymfonyMessage(function (Email $email) use ($bounceEmail) {
            $headers = $email->getHeaders();

            // Add Return-Path for bounce routing
            $headers->addPathHeader('Return-Path', $bounceEmail);

            // Add custom headers for tracking
            $headers->addTextHeader('X-Bounce-Tracking', 'enabled');
            $headers->addTextHeader('X-Mailable-Class', static::class);

            // Set Return-Path on the email object itself
            $email->returnPath($bounceEmail);
        });

        return $message;
    }

    /**
     * Check if the recipient email is suppressed before sending
     */
    protected function checkSuppressionBeforeSending(string $email): bool
    {
        if (MailingBounce::isSuppressed($email)) {
            Log::info("Email sending blocked for suppressed address: {$email}", [
                'mailable_class' => static::class,
                'suppressed' => true
            ]);
            return false;
        }

        return true;
    }

    /**
     * Get the recipient email address from the mailable
     * Override this method in your mailable if the email is not in a standard location
     */
    protected function getRecipientEmail(): ?string
    {
        // Try to extract email from common properties
        if (isset($this->to) && is_array($this->to) && count($this->to) > 0) {
            return $this->to[0]['address'] ?? null;
        }

        // Try other common patterns
        if (property_exists($this, 'recipient') && $this->recipient) {
            return is_string($this->recipient) ? $this->recipient : ($this->recipient->email ?? null);
        }

        if (property_exists($this, 'user') && $this->user) {
            return $this->user->email ?? null;
        }

        if (property_exists($this, 'email') && is_string($this->email)) {
            return $this->email;
        }

        return null;
    }
}