<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\Vision\VectorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use RuntimeException;

final class ImageSearchController extends Controller
{
    public function __construct(private readonly VectorService $vectors)
    {
    }

    public function __invoke(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'image' => ['required', 'file', 'image', 'max:10240'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:24'],
        ]);

        if (! $this->vectors->isConfigured()) {
            return response()->json([
                'data' => [],
                'reason' => 'vector_gateway_not_configured',
            ], 503);
        }

        $limit = (int) ($payload['limit'] ?? 12);

        try {
            $items = $this->vectors->searchByUploadedImage($payload['image'], $limit);
        } catch (RuntimeException $e) {
            return response()->json([
                'data' => [],
                'reason' => 'vector_gateway_error',
                'message' => $e->getMessage(),
            ], 502);
        }

        return response()->json([
            'data' => $items,
            'meta' => [
                'source' => 'vector_gateway',
                'limit' => $limit,
            ],
        ]);
    }
}
