<?php

namespace App\Domains\UserManagement\Actions\GenerateActivationToken;

use App\Domains\MessageSystem\Actions\SendMessage\SendMessageCommand;
use App\Domains\MessageSystem\Actions\SendMessage\SendMessageRequest;
use App\Enumerations\MessageType;
use App\MessageTemplates\activationCodeTemplate;
use App\ValueObjects\EmailAddress;
use App\ValueObjects\MessageRecipient;
use Illuminate\Support\Str;

class GenerateActivationTokenCommand {
    private GenerateActivationTokenRequest $request;

    public function __construct(GenerateActivationTokenRequest $request) {
        $this->request = $request;
    }

    public function execute() : GenerateActivationTokenResponse {
        $response = new GenerateActivationTokenResponse;

        $activationCode = Str::password(24,true,true,false,false);
        $this->request->user->activation_token = $activationCode;
        if (null !== $this->request->expirationDate) {
            $this->request->user->activation_token_expires_at = $this->request->expirationDate;
        }
        $this->request->user->save();

        $response->activationCode = $activationCode;

        $activationMessage = new activationCodeTemplate();
        $activationMessage->composeMessage(EmailAddress::fromString($this->request->user->email), $activationCode);

        $recipient = new MessageRecipient();
        $recipient->addEmailAddress(EmailAddress::fromString($this->request->user->email));
        $recipient->setName($this->request->user->getFullname());

        $message = activationCodeTemplate::createForUser(EmailAddress::fromString($this->request->user->email), $activationCode);

        $userMessageRequests = new SendMessageRequest($message->getMessage(), $message->getSubject(), $recipient, [MessageType::EMAIL]);

        $userMessageCommand = new SendMessageCommand($userMessageRequests);
        $userMessageCommand->send();

        return $response;

    }
}
