<?php

namespace App\Providers;

use App\Mail\MailpitCopyListener;
use App\Mail\UniversalBounceHandler;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class MailBounceServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this->app->singleton(UniversalBounceHandler::class);
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Copy to Mailpit first (before bounce handler which may return false and halt propagation)
        Event::listen(MessageSending::class, [MailpitCopyListener::class, 'handle']);

        // Register the universal bounce handler for all outgoing emails
        Event::listen(MessageSending::class, [UniversalBounceHandler::class, 'handle']);
    }
}