<?php

namespace App\Http\Controllers\Api\Advisories;

use App\Http\Controllers\Controller;
use App\Models\Advisories\Advisory;
use App\Services\Filters\FiltersService;
use App\Transformers\Advisories\AdvisoryTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdvisoriesController extends Controller {
    protected Advisory $model;

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

    public function index(Request $request): JsonResponse {
        $query = $this->model->query();
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new AdvisoryTransformer())->respond();
    }

    public function show(Request $request, $id): JsonResponse {
        $query = $this->model->query();
        $model = ($id === 'main') ? $query->where(['is_main' => 1])->firstOrFail() : $query->byUuid($id)->firstOrFail();
        return fractal($model, new AdvisoryTransformer())->respond();
    }

    public function siblings(Request $request, $id): JsonResponse {
        $filters = collect($request->has('filters') ? json_decode($request->get('filters'), true) : []);
        $query = $this->model->query();
        $model = ($id === 'main') ? $query->where(['is_main' => 1])->firstOrFail() : $query->byUuid($id)->firstOrFail();
        $query = $model->siblings();
        $service = FiltersService::getService('advisories');
        $service->applyFilters($query, $filters);
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new AdvisoryTransformer())->respond();
    }

    public function store(Request $request): JsonResponse {
        $this->validate($request, [
            'parent' => 'required|exists:advisories,uuid',
            'title' => 'required',
            'number' => 'required',
            'type' => 'required'
        ]);

        $model = $this->model->create($request->all());
        return fractal($model, new AdvisoryTransformer())->respond(201);
    }

    public function update(Request $request, $uuid): JsonResponse	{
        $model = $this->model->byUuid($uuid)->firstOrFail();
        $this->validate($request, [
            'title' => 'required',
            'number' => 'required',
            'type' => 'required'
        ]);
        $model->update($request->all());
        return fractal($model->fresh(), new AdvisoryTransformer())->respond();
    }

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


}
