<?php

namespace App\Http\Controllers\Api;

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

class QuestionSearchController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $query = Question::query();

        if ($search = $request->string('q')->toString()) {
            $query->search($search);
        }

        if ($kpCode = $request->string('kp_code')->toString()) {
            $query->where('kp_code', $kpCode);
        }

        if ($type = $request->string('question_type')->toString()) {
            $query->where('question_type', $type);
        }

        $min = $request->float('difficulty_min');
        $max = $request->float('difficulty_max');
        if ($min !== null && $max !== null) {
            $query->whereBetween('difficulty', [$min, $max]);
        }

        $perPage = max(1, min(50, (int) $request->input('per_page', 20)));

        return response()->json($query->paginate($perPage));
    }
}
