<?php

namespace App\Listeners;

use App\Contracts\WhatsAppServiceContract;
use App\Models\User;
use Illuminate\Mail\Events\MessageSent;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class SendWhatsAppOnMailSent
{
    public function __construct(
        private readonly WhatsAppServiceContract $whatsapp,
    ) {}

    public function handle(MessageSent $event): void
    {
        if (! $this->whatsapp->isEnabled()) {
            return;
        }

        $email = $this->resolveEmail($event);

        if (! $email instanceof Email) {
            return;
        }

        if ($this->isPlatformNotification($email)) {
            return;
        }

        $message = $this->buildMessage($email);

        if ($message === '') {
            return;
        }

        foreach ($this->recipientEmails($email) as $recipientEmail) {
            $user = User::query()->where('email', $recipientEmail)->first();

            if (! $user?->phone) {
                continue;
            }

            $this->whatsapp->send($user->phone, $message);
        }
    }

    private function resolveEmail(MessageSent $event): ?Email
    {
        $original = $event->sent->getOriginalMessage();

        return $original instanceof Email ? $original : null;
    }

    /**
     * @return list<string>
     */
    private function recipientEmails(Email $email): array
    {
        $emails = [];

        foreach (['getTo', 'getCc', 'getBcc'] as $method) {
            foreach ($email->{$method}() as $address) {
                if ($address instanceof Address) {
                    $emails[] = $address->getAddress();
                }
            }
        }

        return array_values(array_unique($emails));
    }

    private function isPlatformNotification(Email $email): bool
    {
        return $email->getHeaders()->has('X-Platform-Notification');
    }

    private function buildMessage(Email $email): string
    {
        $subject = trim((string) $email->getSubject());
        $body = trim(strip_tags((string) ($email->getTextBody() ?: $email->getHtmlBody() ?: '')));
        $body = html_entity_decode($body, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $body = preg_replace('/\s+/', ' ', $body) ?? '';

        if ($subject !== '' && $body !== '') {
            return $subject."\n\n".$body;
        }

        return $subject !== '' ? $subject : $body;
    }
}
