<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Question;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PaperAssembleController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $count = max(1, min(200, (int) $request->input('count', 10)));
        $kpCodes = (array) $request->input('kp_codes', []);
        $types = (array) $request->input('question_types', []);

        $query = Question::query();

        if (!empty($kpCodes)) {
            $query->whereIn('kp_code', $kpCodes);
        }

        if (!empty($types)) {
            $query->whereIn('question_type', $types);
        }

        $stageGrade = $this->normalizeStageGrade((int) $request->input('grade'));
        if ($stageGrade !== null) {
            $query->where('grade', $stageGrade);
        }

        $questions = $query->inRandomOrder()->limit($count)->get();

        return response()->json([
            'count' => $questions->count(),
            'data' => $questions,
        ]);
    }

    private function normalizeStageGrade(int $grade): ?int
    {
        if ($grade <= 0) {
            return null;
        }

        return $grade <= 9 ? 2 : 3;
    }
}
