<?php

namespace Daylight\Core\Http\Controllers\API;

use Daylight\Core\Models\Contracts\Relatable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController
{
    public function __invoke(Request $request): JsonResponse
    {
        $model = $request->get('model');
        $query = $request->get('query', '');
        $selected = array_filter(explode(',', $request->get('selected', '')));
        $limit = min((int) $request->get('limit', 10), 50); // Max 50 results

        // Resolve model class
        $modelClass = $this->resolveModelClass($model);
        if (! $modelClass) {
            return response()->json(['error' => 'Invalid model: ' . $model], 400);
        }

        // Check if model implements Relatable contract
        if (! in_array(Relatable::class, class_implements($modelClass))) {
            return response()->json(['error' => 'Model does not implement Relatable contract'], 400);
        }

        $results = collect();

        // Always include selected items first (even if they don't match search)
        if (! empty($selected)) {
            $results = $modelClass::getForRelation($selected);
        }

        // Add search results (excluding already selected)
        if (strlen($query) >= 2) {
            $searchResults = $modelClass::searchForRelation($query, $selected, $limit);
            $results = $results->merge($searchResults)->unique('id')->take($limit);
        }

        return response()->json([
            'results' => $results->values(),
            'hasMore' => false, // Could implement pagination later
        ]);
    }

    private function resolveModelClass(string $model): ?string
    {
        // Expect full class names only (e.g., Daylight\Core\Models\Product)
        return class_exists($model) ? $model : null;
    }
}
