<?php

namespace App\Http\Controllers\Api\Pages;

use App\Http\Controllers\Controller;
use App\Models\Pages\Page;
use App\Models\Publications\Publication;
use App\Services\Filters\FiltersService;
use App\Transformers\Pages\PageTransformer;
use App\Transformers\Publications\PublicationTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PagesController extends Controller {
    protected Page $model;

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

    public function root(Request $request): JsonResponse {
        return fractal(Page::root(), new PageTransformer())->respond();
    }

    public function find(Request $request): ?JsonResponse {
        if ($model = Page::byUrl($request->get('url'))) {
            return fractal($model, new PageTransformer())->respond();
        } elseif ($model = Publication::byUrl($request->get('url'))) {
            return fractal($model, new PublicationTransformer())->respond();
        }
        return null;
    }

    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('pages');
        $service->applyFilters($query, $filters);
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new PageTransformer())->respond();
    }

    public function show(Request $request, $id): JsonResponse {
        $model = $this->model->byUuid($id)->firstOrFail();
        return fractal($model, new PageTransformer())->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);
    }

}
