<?php

namespace App\Classes\Modules\ControllersLogic\Accounts;

use App\Classes\Modules\Accounts\DataTransferObjects\UserInvitationObject;
use App\Classes\Modules\Accounts\Services\CreatesUserInvitation;
use App\Classes\Modules\Accounts\Validation\CanSendAccountInvitation;
use App\Classes\Modules\ControllerLogic\Exceptions\InternalServerErrorException;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Events\Accounts\UserInvited;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateAccountInvitationLogic
{

    /** @var CreatesUserInvitation */
    private $createUserInvitation;

    /** @var CanSendAccountInvitation */
    private $canSendAccountInvitation;

    /**
     * CreateAccountInvitationLogic constructor.
     * @param CreatesUserInvitation $createUserInvitation
     * @param CanSendAccountInvitation $canSendAccountInvitation
     */
    public function __construct(CreatesUserInvitation $createUserInvitation, CanSendAccountInvitation $canSendAccountInvitation)
    {
        $this->createUserInvitation = $createUserInvitation;
        $this->canSendAccountInvitation = $canSendAccountInvitation;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws InternalServerErrorException
     */
    public function execute(Request $request) {

        try {
            $object = new UserInvitationObject($request->get('role_id'), $request->get('email'));

            if($this->canSendAccountInvitation->execute($object)){


                $invitation = $this->createUserInvitation->execute($object);
                event(new UserInvited($invitation));

                return new JsonResponse("Invitation have been sent!", HttpStatus::RESOURCE_CREATED);
            }

        } catch (\Exception $exception) {
            throw new InternalServerErrorException("Failed to send user invitation because {$exception->getMessage()}");
        }
    }
}