<?php

namespace App\Http\Controllers\Api\Applications;

use App\Http\Controllers\Controller;
use App\Models\Applications\Application;
use App\Services\Filters\FiltersService;
use App\Transformers\Applications\ApplicationTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApplicationsController extends Controller {
    protected Application $model;

    public function __construct(Application $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;});
        $query = $this->model->query();
        $service = FiltersService::getService('applications');
        $service->applyFilters($query, $filters);
        $query->orderBy('id', 'desc');
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new ApplicationTransformer())->respond();
    }

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

    public function store(Request $request) {
    }

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

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


}
