<?php

namespace App\Classes\Modules\Milestones\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Rewards\Services\FetchesReward;
use App\Classes\Modules\Milestones\Processors\UpdateMilestoneProcessor;
use App\Classes\Modules\Milestones\Processors\AssignRewardProcessor;
use App\Classes\Modules\Milestones\DataTransferObjects\AchievementObject;
use App\Http\Resources\MilestoneResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Reward;

class UpdateMilestoneLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Update Milestone',
            'message' => 'You have successfully updated a milestone'
        ];
    }

    /** @var FetchesReward */
    private $fetchesReward;

    /** @var UpdateMilestoneProcessor */
    private $updateMilestoneProcessor;

    /** @var AssignRewardProcessor */
    private $assignRewardProcessor;

    /**
     * UpdateMilestoneLogic constructor.
     * @param UpdateMilestoneProcessor $updateMilestoneProcessor
     * @param FetchesReward $fetchesReward
     * @param AssignRewardProcessor $assignRewardProcessor
     */
    public function __construct(UpdateMilestoneProcessor $updateMilestoneProcessor, FetchesReward $fetchesReward, AssignRewardProcessor $assignRewardProcessor)
    {
        $this->updateMilestoneProcessor = $updateMilestoneProcessor;
        $this->fetchesReward = $fetchesReward;
        $this->assignRewardProcessor = $assignRewardProcessor;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request) : JsonResponse
    {
        $milestone = $this->updateMilestoneProcessor->execute($request);

        //Extra checking to make sure that each reward exists
        $rewardIds = $request->input('reward_ids');
        foreach ($rewardIds as $rewardId) {
            /** @var Reward $reward */
            $this->fetchesReward->execute(['id' => $rewardId]);
        }

        $object = new AchievementObject($milestone, $rewardIds);
        $this->assignRewardProcessor->execute($object);

        return $this->resourceResponse(new MilestoneResource($milestone));
    }
}
