<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BlogTag extends Model
{
    protected $fillable = ['name', 'slug'];

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function posts(): BelongsToMany
    {
        return $this->belongsToMany(BlogPost::class, 'blog_post_tag', 'tag_id', 'post_id');
    }

    public function publishedPosts(): BelongsToMany
    {
        return $this->posts()->published();
    }

    public function url(): string
    {
        return url('blog/tags/' . $this->slug);
    }

    public static function generateSlug(string $name, ?int $excludeId = null): string
    {
        $base = str_replace(' ', '-', trim($name));
        $slug = $base;
        $counter = 1;

        while (
            static::where('slug', $slug)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists()
        ) {
            $slug = $base . '-' . $counter++;
        }

        return $slug;
    }

    public static function findOrCreateByName(string $name): self
    {
        $name = trim($name);
        return static::firstOrCreate(
            ['name' => $name],
            ['slug' => static::generateSlug($name)]
        );
    }
}
