<?php

namespace App\Classes\Modules\Accounts\ControllersLogic;

use App\Http\Resources\UserResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Accounts\Services\FetchesUser;

use App\Classes\Modules\Accounts\Standards\Rules\CanDeleteUser;
use App\Classes\Modules\Accounts\Services\DeletesUser;

use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DeleteUserLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Delete User',
            'message' => 'You have successfully deleted the User'
        ];
    }

    /** @var CanDeleteUser */
    private $canDeleteUser;

    /** @var DeletesUser */
    private $deletesUser;

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


    public function __construct(
        CanDeleteUser $canDeleteUser,
        DeletesUser $deletesUser,
        FetchesUser $fetchesUser
    ) {
        $this->canDeleteUser = $canDeleteUser;
        $this->deletesUser = $deletesUser;
        $this->fetchesUser = $fetchesUser;
    }

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

            $user = $this->fetchesUser->execute(['id' => $request->route('id')]);
            $this->canDeleteUser->passes();
            $this->deletesUser->execute($user);

            DB::commit();

            return $this->resourceResponse(new UserResource($user));
        } catch (\Exception $exception) {
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }
    }
}
