<?php

namespace App\Classes\Modules\Accounts\Services;

use App\Classes\Modules\Accounts\DataTransferObjects\UserObject;
use App\Classes\Modules\Accounts\Exceptions\CannotCreateOrderException;
use App\Classes\Modules\ControllerLogic\Exceptions\ResourceConflictException;
use App\Models\User;
use App\Traits\DeterminesIfUserPasswordMatchesRequirements;
use Illuminate\Support\Facades\Hash;

class CreatesUserAccount {
    use DeterminesIfUserPasswordMatchesRequirements;

    /** @var User */
    private $repository;

    /** @var CreatesEmailVerificationAttempt */
    private $service;

    /**
     * @param User $repository
     * @param CreatesEmailVerificationAttempt $service
     */
    public function __construct(
        User $repository,
        CreatesEmailVerificationAttempt $service
    ) {
        $this->repository = $repository;
        $this->service    = $service;
    }

    /**
     * @param UserObject $object
     *
     * @return User
     * @throws CannotCreateOrderException
     */
    public function execute(UserObject $object): ?User {

        try {

            // verify if the email already exists in the database
            if($this->repository->where('email', $object->getEmail())->get()->count()){
                throw new ResourceConflictException();
            }
            /** @var User $user */
            $user = $this->repository->create([
                'first_name'    => $object->getFirstName(),
                'last_name'    => $object->getLastName(),
                'email'    => $object->getEmail(),
                'role_id' => $object->getRoleId(),
                'password' => Hash::make($object->getPassword())
            ]);
//            // create an email verification attempt if needed
//            if ($object->isVerified() === false) {
//                $this->service->execute($object->getEmail());
//            }

            return $user;

        } catch (\Exception $exception) {
            throw new CannotCreateOrderException($exception->getMessage());
        }
    }
}
