<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Content\StoreContentCategoryRequest;
use App\Http\Requests\Content\UpdateContentCategoryRequest;
use App\Services\ContentCategoryService;
use Illuminate\Http\Request;

class ContentCategoryController extends Controller
{
    protected $categoryService;

    public function __construct(ContentCategoryService $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    public function index(Request $request)
    {
        $result = $this->categoryService->index($request->all());

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

    public function tree(Request $request)
    {
        $result = $this->categoryService->tree();

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

    public function store(StoreContentCategoryRequest $request)
    {
        $result = $this->categoryService->store($request->validated());

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

    public function show($id)
    {
        $result = $this->categoryService->show((int) $id);

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

    public function update(UpdateContentCategoryRequest $request, $id)
    {
        $result = $this->categoryService->update($id, $request->validated());

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

    public function destroy($id)
    {
        $result = $this->categoryService->destroy($id);

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

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:0,1',
        ]);

        $result = $this->categoryService->updateStatus($id, $request->status);

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

    public function saveSort(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'sorts' => 'required|array',
            'sorts.*' => 'integer',
        ]);

        $result = $this->categoryService->saveSort($request->ids, $request->sorts);

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