<?php

namespace App\Http\Controllers\Api\Objects;

use App\Http\Controllers\Controller;
use App\Models\Objects\ObjectType;
use App\Transformers\Objects\ObjectTypeTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ObjectTypesController extends Controller {
    protected ObjectType $model;

    public function __construct(ObjectType $model) {
        $this->model = $model;
    }

    public function index(Request $request): JsonResponse {
        $parent = ($val = $request->get('parent')) ? $this->model->byUuidOrName($val)->first() : null;
        $query = $parent ? $parent->children() : $this->model->query()->where(['parent_id' => 0]);
        $query->orderBy('id');
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new ObjectTypeTransformer())->respond();
    }

    public function show($id): JsonResponse {
        $model = $this->model->byUuidOrName($id)->firstOrFail();
        return fractal($model, new ObjectTypeTransformer())->respond();
    }

    public function store(Request $request): JsonResponse {
        $this->validate($request, [
            'name' => 'required',
            'title' => 'required'
        ]);
        $model = $this->model->create($request->all());
        return fractal($model, new ObjectTypeTransformer())->respond(201);
    }

    public function update(Request $request, $uuid): JsonResponse {
        $model = $this->model->byUuidOrName($uuid)->firstOrFail();
        $this->validate($request, [
            'name' => 'sometimes|required',
            'title' => 'sometimes|required'
        ]);
        $model->update($request->all());
        return fractal($model->fresh(), new ObjectTypeTransformer())->respond();
    }

    public function destroy(Request $request, $uuid): JsonResponse {
        $model = $this->model->byUuidOrName($uuid)->firstOrFail();
        $model->delete();
        return response()->json(null, 204);
    }
}
