<?php

namespace App\Classes\Modules\Accounts\ControllersLogic;

use App\Classes\Modules\Accounts\DataTransferObjects\AuthenticationCredentialsObject;
use App\Classes\Modules\Accounts\Services\AuthenticatesUser;
use App\Classes\Modules\Accounts\Services\AuthenticationRedirect;
use App\Classes\Modules\Accounts\Standards\Rules\CanAuthenticateUser;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\ValueObjects\Constants\Notifications;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AuthenticateUserLogic extends AbstractControllerLogic
{

    protected function notification():array {
        return Notifications::AUTHENTICATION;
    }

    /** @var CanAuthenticateUser */
    private $canAuthenticateUser;

    /** @var AuthenticatesUser */
    private $authenticatesUser;

    /** @var AuthenticationRedirect */
    private $authenticationRedirect;

    /**
     * AuthenticateUserLogic constructor.
     * @param CanAuthenticateUser $canAuthenticateUser
     * @param AuthenticatesUser $authenticatesUser
     * @param AuthenticationRedirect $authenticationRedirect
     */
    public function __construct(CanAuthenticateUser $canAuthenticateUser, AuthenticatesUser $authenticatesUser, AuthenticationRedirect $authenticationRedirect)
    {
        $this->canAuthenticateUser = $canAuthenticateUser;
        $this->authenticatesUser = $authenticatesUser;
        $this->authenticationRedirect = $authenticationRedirect;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    protected function logic(Request $request): JsonResponse {

        try {
            $object = new AuthenticationCredentialsObject($request->input('email'),
                $request->input('password'), $request->input('remember_me'));

            $this->canAuthenticateUser->passes($object);

            $token = $this->authenticatesUser->execute($object);

            return $this->response(['access_token' => $token, 'redirect_url' => $this->authenticationRedirect->url()]);

        } catch (\Exception $exception){
            dd($exception);
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }

    }

}