<?php

namespace App\Classes\Modules\Milestones\Processors;

use App\Classes\Modules\Milestones\DataTransferObjects\MilestoneObject;
use App\Classes\Modules\Milestones\Services\FetchesMilestone;
use App\Classes\Modules\Milestones\Services\UpdatesMilestone;
use App\Classes\Modules\Milestones\Standards\Rules\CanUpdateMilestone;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;

class UpdateMilestoneProcessor
{
    /** @var UpdatesMilestone */
    private $updatesMilestone;

    /** @var FetchesMilestone */
    private $fetchesMilestone;

    /** @var CanUpdateMilestone */
    private $canUpdateMilestone;

    /**
     * UpdateMilestoneProcessor constructor.
     * @param UpdatesMilestone $updatesMilestone
     * @param FetchesMilestone $fetchesMilestone
     * @param CanUpdateMilestone $canUpdateMilestone
     */
    public function __construct(CanUpdateMilestone $canUpdateMilestone, UpdatesMilestone $updatesMilestone, FetchesMilestone $fetchesMilestone)
    {
        $this->canUpdateMilestone = $canUpdateMilestone;
        $this->updatesMilestone = $updatesMilestone;
        $this->fetchesMilestone = $fetchesMilestone;
    }


    /**
     * @param Request $request
     * @return Model
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function execute(Request $request): Model
    {
        $milestoneObject = new MilestoneObject(
            $request->input('id'),
            $request->input('name'),
            $request->input('description')
        );

        $this->canUpdateMilestone->passes($milestoneObject);

        $milestone = $this->fetchesMilestone->execute(['id' => $request->route('id')]);

        return $this->updatesMilestone->execute($milestone, $milestoneObject);
    }

}
