<?php

namespace App\Http\Controllers\Api\Registries;

use App\Http\Controllers\Controller;
use App\Models\Registries\Category;
use App\Models\Registries\Entry;
use App\Models\Registries\Registry;
use App\Services\Filters\FiltersService;
use App\Transformers\Registries\EntryTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EntriesController extends Controller {
    protected Entry $model;

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

    public function index(Request $request): JsonResponse {
        $filters = collect($request->has('filters') ? json_decode($request->get('filters'), true) : [])->filter(function($val) {return $val;});
        //$registry = Registry::byUuid($request->get('registry'))->first();
        //$category = Category::byUuid($request->get('category'))->first();
        $query = $this->model->query();
        //if ($filters->except('registry')->isEmpty()) $query->where(['category_id' => $category->id ?? 0]);
        $service = FiltersService::getService('registryEntries');
        $service->applyFilters($query, $filters);
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new EntryTransformer())->respond();
    }

    public function show(Request $request, $id): JsonResponse {
        $model = $this->model->byUuid($id)->firstOrFail();
        return fractal($model, new EntryTransformer())->respond();
    }


    public function store(Request $request): void {
    }


    public function update(Request $request, $uuid): void	{
    }

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