<?php

namespace Fivable\Buildable\Controllers;

use Fivable\Buildable\Models\BuildableSetting;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Fivable\Scaffolding\Controllers\ApiController;

class BuildableSettingController extends ApiController
{
    /**
     * Get all BuildableSettings
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request) : JsonResponse
    {
        $type_mask = $request->type_mask ?? /*all*/NULL;

        $this->authorizeForUser($this->user(), 'viewIndex', BuildableSetting::class, $type_mask);

        $settings = BuildableSetting::indexFor($type_mask);

        return response()->json([
            'settings' => $settings,
        ]);
    }

    /**
     * Update a specific BuildableSetting
     * @param  Request  $request
     * @return JsonResponse
     */
    public function update(Request $request) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'update', BuildableSetting::class, $request->type_mask);

        $buildableSettings = BuildableSetting::updateAll($request->all());

        return response()->json([
            'settings' => $buildableSettings,
        ]);
    }

    /**
     * Return the Buildable JSON grouped by category
     * @return JsonResponse
     */
    public function buildableJsonByCategory() : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'buildableJsonByCategory', BuildableSetting::class);

        $buildableJsonByCategory = BuildableSetting::buildableJsonByCategory();

        return response()->json([
            'buildable_json_by_category' => $buildableJsonByCategory,
        ]);
    }
}
