<?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\CourseChapter;

/**
 * 课程章节控制器
 */
class CourseChapterController extends Controller
{
    public function index(Request $request, int $course): JsonResponse
    {
        $chapters = CourseChapter::where('course_id', $course)
            ->whereNull('parent_id')
            ->with('children')
            ->orderBy('sort')
            ->get();

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

    public function store(Request $request, int $course): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:200',
            'parent_id' => 'nullable|exists:course_chapters,id',
            'sort' => 'nullable|integer',
            'type' => 'nullable|in:video,document',
            'content' => 'nullable|string',
            'video_url' => 'nullable|string|max:500',
            'duration' => 'nullable|integer',
        ]);

        $validated['course_id'] = $course;
        $chapter = CourseChapter::create($validated);

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

    public function update(Request $request, int $course, CourseChapter $chapter): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'sometimes|string|max:200',
            'parent_id' => 'nullable|exists:course_chapters,id',
            'sort' => 'nullable|integer',
            'type' => 'nullable|in:video,document',
            'content' => 'nullable|string',
            'video_url' => 'nullable|string|max:500',
            'duration' => 'nullable|integer',
        ]);

        $chapter->update($validated);

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

    public function destroy(int $course, CourseChapter $chapter): JsonResponse
    {
        $chapter->delete();

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