<?php
namespace App\Classes\Modules\Companies\ControllersLogic;

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

class UpdateCompanyNameAndDebtorLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Update Company Account Status',
            'message' => 'You have successfully updated the Company Account Status'
        ];
    }
    /** @var CanUpdateCompany */
    private $canUpdateCompany;

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

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

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

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

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        $query = $this->fetchesCompany->execute(['id' => $request->route('id')]);

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

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

        $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));
    }

}

