<?php

namespace App\Classes\Modules\Companies\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\UpdatesCompany;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Companies\Standards\Rules\CanUpdateCompany;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Http\Resources\CompanyResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateCompanyLogic extends AbstractControllerLogic
{

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

    /** @var CanUpdateCompany */
    private $canUpdateCompany;

    /** @var UpdatesCompany */
    private $updatesCompany;

    /** @var FetchesCompany */
    private $fetchesCompany;

    /**
     * UpdateCompanyControllersLogic constructor.
     * @param CanUpdateCompany $canUpdateCompany
     * @param UpdatesCompany $updatesCompany
     * @param FetchesCompany $fetchesCompany
     */
    public function __construct(CanUpdateCompany $canUpdateCompany, UpdatesCompany $updatesCompany, FetchesCompany $fetchesCompany)
    {
        $this->canUpdateCompany = $canUpdateCompany;
        $this->updatesCompany = $updatesCompany;
        $this->fetchesCompany = $fetchesCompany;
    }


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

            $object = new CompanyObject($request->input('reference_no'), $request->input('name'), $request->input('type'));

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

            $query = $this->fetchesCompany->execute(['id' => $request->route('id')]);

            $query = $this->updatesCompany->execute($query, $object);

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


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

    }

}