<?php

namespace App\Http\Controllers\Admin\Kb;

use App\Http\Controllers\Controller;
use App\Models\Kb\KbCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class KbCategoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = KbCategory::query()->with('children');
        $query->when($request->filled('status'), fn($q) => $q->where('status', $request->status));
        $query->where('parent_id', 0);

        return $this->success($query->orderBy('sort')->orderBy('id')->get());
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'parent_id' => 'nullable|integer|min:0',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);
        $validated['parent_id'] = $validated['parent_id'] ?? 0;

        $category = KbCategory::create($validated);
        return $this->success($category);
    }

    public function show(KbCategory $kbCategory): JsonResponse
    {
        return $this->success($kbCategory->load('children'));
    }

    public function update(Request $request, KbCategory $kbCategory): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'parent_id' => 'nullable|integer|min:0',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);
        $kbCategory->update($validated);
        return $this->success($kbCategory);
    }

    public function destroy(KbCategory $kbCategory): JsonResponse
    {
        if ($kbCategory->children()->exists()) {
            return $this->error('请先删除子分类');
        }
        if ($kbCategory->articles()->exists()) {
            return $this->error('该分类下还有文章，无法删除');
        }
        $kbCategory->delete();
        return $this->success(null);
    }
}
