<?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\CreateMilestoneProcessor;
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 CreateMilestoneLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Create Milestone',
            'message' => 'You have successfully created a milestone'
        ];
    }

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

    /** @var CreateMilestoneProcessor */
    private $createMilestoneProcessor;

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

    /**
     * CreateMilestoneLogic constructor.
     */
    public function __construct(CreateMilestoneProcessor $createMilestoneProcessor, FetchesReward $fetchesReward, AssignRewardProcessor $assignRewardProcessor)
    {
        $this->createMilestoneProcessor = $createMilestoneProcessor;
        $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->createMilestoneProcessor->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));
    }
}
