<?php

namespace App\Http\Controllers\Api;

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

class KnowledgeRecommendController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $kpCode = $request->string('kp_code')->toString();
        if ($kpCode !== '') {
            $kp = KnowledgePoint::query()->where('kp_code', $kpCode)->first();
            if ($kp) {
                return response()->json([
                    'kp_code' => $kp->kp_code,
                    'related_kps' => $kp->related_kp_codes ?? [],
                    'prerequisite_kps' => $kp->prerequisite_kp_codes ?? [],
                    'post_kps' => $kp->dependent_kp_codes ?? [],
                ]);
            }
        }

        $fallback = KnowledgePoint::query()->limit(10)->get(['kp_code', 'name']);

        return response()->json([
            'kp_code' => $kpCode,
            'related_kps' => $fallback->pluck('kp_code'),
            'prerequisite_kps' => [],
            'post_kps' => [],
        ]);
    }
}
