<?php

namespace App\Classes\Modules\SegmentConstants\ControllersLogic;

use App\Http\Resources\ConstantResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Segments\Services\FetchesConstant;

use App\Classes\Modules\Segments\Standards\Rules\CanUpdateConstant;
use App\Classes\Modules\Segments\Services\UpdatesConstant;
use App\Classes\Modules\Segments\DataTransferObjects\ConstantObject;

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

class UpdateSegmentConstantLogic extends AbstractControllerLogic
{

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

    /** @var CanUpdateConstant */
    private $canUpdateConstant;

    /** @var UpdatesConstant */
    private $updatesConstant;

    /** @var FetchesConstant */
    private $fetchesConstant;


    /**
     * UpdateSegmentLogic constructor.
     * @param CanUpdateConstant $canUpdateConstant
     * @param UpdatesConstant $updatesConstant
     * @param FetchesConstant $fetchesConstant
     */
    public function __construct(
        CanUpdateConstant $canUpdateConstant, 
        UpdatesConstant $updatesConstant, 
        FetchesConstant $fetchesConstant
    )
    {
        $this->canUpdateConstant = $canUpdateConstant;
        $this->updatesConstant = $updatesConstant;
        $this->fetchesConstant = $fetchesConstant;
    }

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

            $constant_query = $this->fetchesConstant->execute(['id' => $request->route('id')]);

            $constant_object = new ConstantObject(
                $request->input('name', $constant_query->name),
                $request->input('reference', $constant_query->reference),
                $request->input('detail', (array) $constant_query->detail));
            $this->canUpdateConstant->passes($constant_object);
            $constant_query = $this->updatesConstant->execute($constant_query, $constant_object);
           
            DB::commit();

            return $this->resourceResponse(new ConstantResource($constant_query));

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

}