<?php

declare(strict_types=1);

namespace Kylin\Education\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Kylin\Education\Models\CourseCategory;

/**
 * 课程分类控制器
 */
class CourseCategoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $categories = CourseCategory::with('children')
            ->whereNull('parent_id')
            ->orderBy('sort')
            ->get();

        return response()->json(['code' => 0, 'data' => $categories]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'parent_id' => 'nullable|exists:course_categories,id',
            'sort' => 'nullable|integer',
        ]);

        $category = CourseCategory::create($validated);

        return response()->json(['code' => 0, 'data' => $category], 201);
    }

    public function show(CourseCategory $courseCategory): JsonResponse
    {
        $courseCategory->load('children');

        return response()->json(['code' => 0, 'data' => $courseCategory]);
    }

    public function update(Request $request, CourseCategory $courseCategory): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'parent_id' => 'nullable|exists:course_categories,id',
            'sort' => 'nullable|integer',
        ]);

        $courseCategory->update($validated);

        return response()->json(['code' => 0, 'data' => $courseCategory]);
    }

    public function destroy(CourseCategory $courseCategory): JsonResponse
    {
        $courseCategory->delete();

        return response()->json(['code' => 0, 'message' => '删除成功']);
    }
}
