<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\NovaCards;

use App\Http\Controllers\Controller;
use App\Models\NovaCard;
use App\Services\NovaCards\NovaCardAiAssistService;
use App\Services\NovaCards\NovaCardPresenter;
use App\Services\NovaCards\NovaCardRelatedCardsService;
use App\Services\NovaCards\NovaCardRisingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NovaCardDiscoveryController extends Controller
{
    public function __construct(
        private readonly NovaCardPresenter $presenter,
        private readonly NovaCardRisingService $rising,
        private readonly NovaCardRelatedCardsService $related,
        private readonly NovaCardAiAssistService $aiAssist,
    ) {
    }

    /**
     * GET /api/cards/rising
     * Returns recently published cards gaining traction fast.
     */
    public function rising(Request $request): JsonResponse
    {
        $limit = min((int) $request->query('limit', 18), 36);
        $cards = $this->rising->risingCards($limit);

        return response()->json([
            'data' => $this->presenter->cards($cards->all(), false, $request->user()),
        ]);
    }

    /**
     * GET /api/cards/{id}/related
     * Returns related cards for a given card.
     */
    public function related(Request $request, int $id): JsonResponse
    {
        $card = NovaCard::query()->publiclyVisible()->findOrFail($id);
        $limit = min((int) $request->query('limit', 8), 16);
        $relatedCards = $this->related->related($card, $limit);

        return response()->json([
            'data' => $this->presenter->cards($relatedCards->all(), false, $request->user()),
        ]);
    }

    /**
     * GET /api/cards/{id}/ai-suggest
     * Returns AI-assist suggestions for the given draft card.
     * The creator must own the card.
     */
    public function suggest(Request $request, int $id): JsonResponse
    {
        $card = NovaCard::query()
            ->where('user_id', $request->user()->id)
            ->findOrFail($id);

        $suggestions = $this->aiAssist->allSuggestions($card);

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