<?php

namespace App\Domains\UserManagement\Actions\UserRegistration;

use App\Domains\MessageSystem\Actions\SendMessage\SendMessageCommand;
use App\Domains\MessageSystem\Actions\SendMessage\SendMessageRequest;
use App\Domains\UserManagement\Actions\GenerateActivationToken\GenerateActivationTokenCommand;
use App\Domains\UserManagement\Actions\GenerateActivationToken\GenerateActivationTokenRequest;
use App\Enumerations\MessageType;
use App\MessageTemplates\Registration\InformAdminAboutNewUserTemplate;
use App\Models\User;
use App\ValueObjects\EmailAddress;
use App\ValueObjects\MessageRecipient;

class UserRegistrationCommand {
    private UserRegistrationRequest $request;

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

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

        $user = User::create([
            'user_role_main' => $this->request->userRoleMain,
            'user_role_local_group' => $this->request->userRoleLocalGroup,
            'username' => $this->request->email->getValue(),
            'local_group' => $this->request->localGroup,
            'firstname' => $this->request->firstname,
            'lastname' => $this->request->lastname,
            'nickname' => $this->request->nickname !== '' ? $this->request->nickname : null,
            'email' => $this->request->email->getValue(),
        ]);

        if ($user === null) {
            return $response;
        }

        $generateActivationCoedeRequest = new GenerateActivationTokenRequest($user, new \DateTime()->add(new \DateInterval('P1D')));
        $generateActivationCoedeDommand = new GenerateActivationTokenCommand($generateActivationCoedeRequest);
        $result = $generateActivationCoedeDommand->execute();

        $user->activation_token = $result->activationCode;

        $siteAdmin = new MessageRecipient();
        $siteAdmin->addEmailAddress(EmailAddress::fromString(env('APP_ADMIN_MAIL')));
        $siteAdmin->setName(env('APP_ADMIN_NAME'));

        $registrationMessage = InformAdminAboutNewUserTemplate::createNew($user);

        $registrationMessageRequest = new SendMessageRequest($registrationMessage->getMessage(), $registrationMessage->getSubject(), $siteAdmin, [MessageType::EMAIL]);
        $registrationMessageCommand = new SendMessageCommand($registrationMessageRequest);
        $registrationMessageCommand->send();

        $response->user = $user;
        $response->success = true;
        return $response;
    }
}
