<?php

namespace App\Trait;

use App\Models\Tag;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

trait HasTags {
    /**
     * Attach a tag to the model (creates it if it doesn't exist by name).
     */
    public function attachTag(string|Tag $tag): void {
        if (is_string($tag)) {
            $tag = Tag::firstOrCreate(
                ['name' => $tag],
                ['slug' => \Illuminate\Support\Str::slug($tag)]
            );
        }

        if (!$this->tags()->where('tags.id', $tag->id)->exists()) {
            $this->tags()->attach($tag);
        }
    }

    /**
     * Get all of the tags for the model.
     */
    public function tags(): MorphToMany {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    /**
     * Detach a tag from the model.
     */
    public function detachTag(string|Tag $tag): void {
        if (is_string($tag)) {
            $tag = Tag::where('name', $tag)->first();
        }

        if ($tag) {
            $this->tags()->detach($tag);
        }
    }

    /**
     * Check if the model has a specific tag.
     */
    public function hasTag(string $name): bool {
        return $this->tags()->where('name', $name)->exists();
    }
}