<?php

declare(strict_types=1);

namespace App\Filament\Components\Form;

use App\Models\Tag;
use Filament\Forms\Components\TagsInput;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class TagsTagsInput extends TagsInput
{
    public static function create($model): static
    {
        return static::make('tags')
            ->label('برچسب‌ها')
            ->afterStateHydrated(function (TagsInput $tagsInput, ?Model $model = null) {
                $tagsInput->state($model?->tags->pluck('name')->toArray() ?? []);
            })
            ->saveRelationshipsUsing(function (Model $record, array $state) use ($model) {
                $tags = collect($state)->map(function ($tagName) use ($model) {
                    return Tag::firstOrCreate(
                        ['name' => $tagName],
                        [
                            'slug' => Str::slug($tagName),
                            'model_type' => $model,
                            'created_by' => Auth::id(),
                        ]
                    );
                });
                $record->tags()->sync($tags->pluck('id'));
            });
    }
}
