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

/**
 * 班级管理控制器
 *
 * 提供班级信息的增删改查及关联课程/教师管理 API。
 */
class StudentClassController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = StudentClass::with(['course', 'teacher']);

        if ($request->filled('course_id')) {
            $query->where('course_id', $request->input('course_id'));
        }

        $classes = $query->paginate($request->input('per_page', 15));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'course_id' => 'nullable|exists:courses,id',
            'teacher_id' => 'nullable|exists:users,id',
            'capacity' => 'nullable|integer|min:1',
        ]);

        $class = StudentClass::create($validated);

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

    public function show(StudentClass $studentClass): JsonResponse
    {
        $studentClass->load(['students.user', 'course', 'teacher']);

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

    public function update(Request $request, StudentClass $studentClass): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'course_id' => 'nullable|exists:courses,id',
            'teacher_id' => 'nullable|exists:users,id',
            'capacity' => 'nullable|integer|min:1',
        ]);

        $studentClass->update($validated);

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

    public function destroy(StudentClass $studentClass): JsonResponse
    {
        $studentClass->delete();

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