<?php

declare(strict_types=1);

namespace App\Services\Vision;

use App\Models\Artwork;
use RuntimeException;

final class ArtworkVectorIndexService
{
    public function __construct(
        private readonly VectorGatewayClient $client,
        private readonly ArtworkVisionImageUrl $imageUrl,
        private readonly ArtworkVectorMetadataService $metadata,
    ) {
    }

    public function isConfigured(): bool
    {
        return $this->client->isConfigured();
    }

    /**
     * @return array{url: string, metadata: array<string, mixed>}
     */
    public function payloadForArtwork(Artwork $artwork): array
    {
        $url = $this->imageUrl->fromArtwork($artwork);
        if ($url === null || $url === '') {
            throw new RuntimeException('No vision image URL could be generated for artwork ' . (int) $artwork->id . '.');
        }

        return [
            'url' => $url,
            'metadata' => $this->metadata->forArtwork($artwork),
        ];
    }

    /**
     * @return array{url: string, metadata: array<string, mixed>}
     */
    public function upsertArtwork(Artwork $artwork): array
    {
        $payload = $this->payloadForArtwork($artwork);

        $this->client->upsertByUrl($payload['url'], (int) $artwork->id, $payload['metadata']);

        $artwork->forceFill([
            'last_vector_indexed_at' => now(),
        ])->save();

        return $payload;
    }
}
