<?php

namespace App\Http\Controllers;

use App\Services\FilterItemService;
use App\Http\Resources\FiltersResource;
use App\Http\Requests\Filter\FilterItemStore;
use App\Services\FilterItemsAssociationService;

class FilterItemController extends Controller
{

    private $filterItemService;

    public function __construct(
        FilterItemService $filterItemService,
        FilterItemsAssociationService $filterItemsAssociationService
    ) {
        $this->filterItemService = $filterItemService;
        $this->filterItemsAssociationService = $filterItemsAssociationService;
        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $filter_items = $this->filterItemService->getAll();

        return response()->json($filter_items, 201);
    }

    public function store(FilterItemStore $request)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $filter_item = $this->filterItemService->save($request->all());

        return response()->json(new FiltersResource($filter_item), 201);
    }

    public function show($id)
    {
        $filter_item = $this->filterItemService->get($id);

        return response()->json($filter_item);
    }

    public function destroy($id)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->filterItemsAssociationService->deleteAllWithFilterItemId($id);

        $this->filterItemService->delete($id);

        return response()->json(null, 204);
    }
}
