<?php

declare(strict_types=1);

namespace App\Services\NovaCards;

use App\Models\NovaCard;
use App\Models\NovaCardTag;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class NovaCardTagService
{
    public function syncTags(NovaCard $card, array $tags): Collection
    {
        $limit = (int) config('nova_cards.validation.max_tags', 8);

        $normalized = collect($tags)
            ->map(static fn ($tag) => trim((string) $tag))
            ->filter(static fn (string $tag): bool => $tag !== '')
            ->map(static fn (string $tag): array => [
                'name' => Str::headline(Str::lower($tag)),
                'slug' => Str::slug($tag),
            ])
            ->filter(static fn (array $tag): bool => $tag['slug'] !== '')
            ->unique('slug')
            ->take($limit)
            ->values();

        $tagIds = $normalized->map(function (array $tag): int {
            $model = NovaCardTag::query()->firstOrCreate(
                ['slug' => $tag['slug']],
                ['name' => $tag['name']]
            );

            return (int) $model->id;
        })->all();

        $card->tags()->sync($tagIds);

        return NovaCardTag::query()->whereIn('id', $tagIds)->get();
    }
}
