<?php

declare(strict_types=1);

namespace App\Services\Vision;

use App\Models\Artwork;
use App\Models\Category;

final class ArtworkVectorMetadataService
{
    /**
     * @return array{content_type: string, category: string, user_id: string, tags: list<string>, is_public: bool, is_deleted: bool, is_nsfw: bool, category_id: int, content_type_id: int, status: mixed}
     */
    public function forArtwork(Artwork $artwork): array
    {
        $artwork->loadMissing([
            'categories' => fn ($categories) => $categories->with('contentType')->orderBy('sort_order')->orderBy('name'),
            'tags:id,slug',
        ]);

        $category = $this->primaryCategory($artwork);

        return [
            'content_type'    => (string) ($category?->contentType?->name ?? ''),
            'category'        => (string) ($category?->name ?? ''),
            'user_id'         => (string) ($artwork->user_id ?? ''),
            'is_public'       => (bool) $artwork->is_public,
            'is_deleted'      => $artwork->trashed(),
            'is_nsfw'         => (bool) $artwork->is_mature,
            'category_id'     => (int) ($category?->id ?? 0),
            'content_type_id' => (int) ($category?->contentType?->id ?? 0),
            'status'          => $artwork->artwork_status,
            'tags' => $artwork->tags
                ->pluck('slug')
                ->map(static fn (mixed $slug): string => trim((string) $slug))
                ->filter(static fn (string $slug): bool => $slug !== '')
                ->unique()
                ->values()
                ->all(),
        ];
    }

    private function primaryCategory(Artwork $artwork): ?Category
    {
        /** @var Category|null $category */
        $category = $artwork->categories->sortBy('sort_order')->first();

        return $category;
    }
}
