<?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\UpdatesCompanyModuleName;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Companies\Standards\Rules\CanUpdateCompany;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Classes\Modules\Companies\Services\UpdatesCompanyDebtor;
use App\Http\Resources\CompanyResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateCompanyNameAndDebtorLogic extends AbstractControllerLogic
{

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

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

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

    /** @var UpdatesCompanyDebtor */
    private $updatesCompanyDebtor;

    /** @var UpdatesCompanyModuleName */
    private $updatesCompanyModuleName;

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


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        $object = new CompanyObject($request->input('name'), $request->input('reference'), $request->input('type'));

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

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

        $this->updatesCompanyModuleName->execute($query->companyModules()->first(), $object->getName());

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

        if ($request->input('debtor') || $query->first()->debtor !== null) {
            $this->updatesCompanyDebtor->execute($query, $request->input('debtor'));
        }

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

}
