<?php

namespace Fivable\Buildable\Controllers;

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

class BuildablePostController extends ApiController
{
    /**
     * Return all BuildablePosts
     * @return JsonResponse
     */
    public function index() : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'viewIndex', BuildablePost::class);

        $posts = BuildablePost::all();

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

    /**
     * Get a specific BuildablePost
     * @param  BuildablePost   $buildablePost
     * @return JsonResponse
     */
    public function show(BuildablePost $buildablePost) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'view', $buildablePost);

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

    /**
     * Create a new BuildablePost
     * @param  Request $request
     * @return JsonResponse
     */
    public function store(Request $request) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'create', BuildablePost::class);

        $newPost = BuildablePost::create($request->all());

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

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

        $buildablePost->update($request->all());

        return response()->json([
            'updated_post' => $buildablePost->fresh(),
        ]);
    }

    /**
     * Delete a specific BuildablePost
     * @param  BuildablePost  $buildablePost
     * @return JsonResponse
     * @throws \Exception
     */
    public function destroy(BuildablePost $buildablePost) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'delete', $buildablePost);

        $buildablePost->delete();

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