<?php

namespace App\Classes\Modules\Accounts\ControllersLogic;

use App\Classes\Modules\Accounts\Services\FetchesUser;
use App\Classes\Modules\Accounts\Standards\Rules\CanFetchUser;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Http\Resources\UserCompanyResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FetchUserByEmailLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Fetch Users',
            'message' => 'You have successfully retrieved the user by email'
        ];
    }

    /** @var CanFetchUser */
    private $canFetchUser;

    /** @var FetchesUser */
    private $fetchesUser;

    /**
     * FetchUserByEmailLogic constructor.
     * @param CanFetchUser $canFetchUser
     * @param FetchesUser $fetchessUser
     */
    public function __construct(CanFetchUser $canFetchUser, FetchesUser $fetchesUser)
    {
        $this->canFetchUser = $canFetchUser;
        $this->fetchesUser = $fetchesUser;
    }

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

            $this->canFetchUser->passes();

            $query = $this->fetchesUser->execute(['email' => $request->route('email')]);

            return $this->resourceResponse(new UserCompanyResource($query));

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

}
