<?php

namespace Fivable\Buildable\Controllers;

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

class BuildableFileController extends ApiController
{
    /**
     * Get all BuildableFiles
     * @return JsonResponse
     */
    public function index() : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'viewIndex', BuildableFile::class);

        $files = BuildableFile::all();

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

    /**
     * @param BuildableFile $buildableFile
     * @return JsonResponse
     */
    public function show(BuildableFile $buildableFile) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'view', $buildableFile);

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

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

        $newFile = BuildableFile::createFile($request);

        if ($newFile) {
            return response()->json([
                'new_file' => $newFile->fresh()
            ]);
        } else {
            return response()->json([
                'error' => 'file creation failed',
            ], 422);
        }
    }

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

        $updatedFile = $buildableFile->updateFile($request);

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

    /**
     * @param BuildableFile $buildableFile
     * @return JsonResponse
     * @throws \Exception
     */
    function destroy(BuildableFile $buildableFile) : JsonResponse
    {
        $this->authorizeForUser($this->user(), 'delete', $buildableFile);

        $buildableFile->delete();
        $buildableFile->deleteInStorage();

        return response()->json([
            'deleted_file' => $buildableFile
        ]);
    }
}
