<?php

declare(strict_types=1);

namespace App\Application\Newsletter\SignUp;

use App\Framework\CommandBus\CommandHandler;
use App\Framework\EventBus\EventBus;
use App\Infrastructure\Api\RapidMailClient;

final readonly class NewsletterSignupHandler
{
    public function __construct(
        private EventBus $eventBus,
    ) {
    }

    #[CommandHandler]
    public function __invoke(SignupUserToNewsletter $command): void
    {
        // RapidMail-Client erstellen und konfigurieren
        $client = new RapidMailClient(
            ApiConfig::RAPIDMAIL_USERNAME->value,
            ApiConfig::RAPIDMAIL_PASSWORD->value
        );

        // Abonnent zur Liste hinzufügen
        $result = $client->addRecipient(
            $command->name,
            $command->email,
            ApiConfig::getRapidmailListId()
        );

        error_log('CommandHandler für: '.$command->email);
        ;

        $this->eventBus->dispatch(new UserWasSignedUp($command->email));
    }
}
