<?php

namespace App\Http\Controllers;

use App\Http\Requests\CategoryRequest;
use App\Models\Category;
use App\Services\CategoryService;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    protected $categoryService;

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

    public function index(\Illuminate\Http\Request $request): JsonResponse
    {
        $level = $request->query('level');
        if ($level) {
            return response()->json($this->categoryService->getByLevel((int)$level));
        }
        return response()->json($this->categoryService->getAllFlat());
    }

    public function manage()
    {
        if (!auth()->user()->hasPermission('manage-categories')) {
            abort(403, 'Unauthorized. Permission manage-categories required.');
        }
        return view('pages.category-master');
    }

    public function store(CategoryRequest $request): JsonResponse
    {
        if (!auth()->user()->hasPermission('manage-categories')) {
            return response()->json(['message' => 'Unauthorized. Permission manage-categories required.'], 403);
        }
        $category = $this->categoryService->createCategory($request->validated());
        return response()->json($category, 201);
    }

    public function update(CategoryRequest $request, Category $category): JsonResponse
    {
        if (!auth()->user()->hasPermission('manage-categories')) {
            return response()->json(['message' => 'Unauthorized. Permission manage-categories required.'], 403);
        }
        $this->categoryService->updateCategory($category, $request->validated());
        return response()->json($category);
    }

    public function destroy(Category $category): JsonResponse
    {
        if (!auth()->user()->hasPermission('manage-categories')) {
            return response()->json(['message' => 'Unauthorized. Permission manage-categories required.'], 403);
        }
        $this->categoryService->deleteCategory($category);
        return response()->json(null, 204);
    }
}
