<?php

namespace App\Http\Controllers;

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

class FilterController extends Controller
{

    private $filterService;
    private $filterItemService;

    public function __construct(FilterService $filterService, FilterItemService $filterItemService)
    {
        $this->filterService = $filterService;
        $this->filterItemService = $filterItemService;
        $this->middleware('auth:sanctum', [
            'except' => [
                'index', 'show'
            ]
        ]);
    }

    public function index()
    {
        $filters = $this->filterService->with(['items']);

        return response()->json(FiltersResource::collection($filters), 201);
    }

    public function indexWithCount()
    {
        $filters = $this->filterService->withCount(['items']);

        return response()->json(FiltersResource::collection($filters), 201);
    }

    public function store(FilterStore $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 = $this->filterService->save($request->all());

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

    public function show($id)
    {
        $filter = $this->filterService->getOneWith($id, ['items']);

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

    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->filterService->delete($id);
        return response()->json(null, 204);
    }
}
