<?php

namespace App\Classes\Modules\Segments\ControllersLogic;

use App\Http\Resources\SegmentResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

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

use App\Classes\Modules\Segments\Standards\Rules\CanUpdateSegment;
use App\Classes\Modules\Segments\Services\UpdatesSegment;
use App\Classes\Modules\Segments\DataTransferObjects\SegmentObject;

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

class UpdateSegmentLogic extends AbstractControllerLogic
{

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

    /** @var CanUpdateSegment */
    private $canUpdateSegment;

    /** @var UpdatesSegment */
    private $updatesSegment;

    /** @var FetchesSegment */
    private $fetchesSegment;


    /**
     * UpdateSegmentLogic constructor.
     * @param CanUpdateSegment $canUpdateSegment
     * @param UpdatesSegment $updatesSegment
     * @param FetchesSegment $fetchesSegment
     */
    public function __construct(
        CanUpdateSegment $canUpdateSegment, 
        UpdatesSegment $updatesSegment, 
        FetchesSegment $fetchesSegment
    )
    {
        $this->canUpdateSegment = $canUpdateSegment;
        $this->updatesSegment = $updatesSegment;
        $this->fetchesSegment = $fetchesSegment;
    }

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

            $segment_query = $this->fetchesSegment->execute(['id' => $request->route('id')]);

            $segment_object = new SegmentObject(
                $request->input('name', $segment_query->name)
            );
            $this->canUpdateSegment->passes($segment_object);
            $segment_query = $this->updatesSegment->execute($segment_query, $segment_object);
           
            DB::commit();

            return $this->resourceResponse(new SegmentResource($segment_query));

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

}