<?php

namespace App\Trait;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait HasSlug {

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

    /**
     * Boot the HasSlug trait for a model.
     * Registers the 'creating' event listener to generate the UUID slug.
     */
    public static function bootHasSlug(): void {
        static::creating(function (Model $model) {
            $slugTarget = $model->getSlugTargetAttribute();

            if (empty($model->{$slugTarget})) {
                $model->{$slugTarget} = $model->generateUniqueSlug();
            }
        });
    }

    /**
     * Define the target attribute where the slug will be stored.
     * Override this in the model if the target is not 'slug'.
     */
    protected function getSlugTargetAttribute(): string {
        return 'slug';
    }

    /**
     * Generate a unique slug as a UUID (Universally Unique Identifier).
     * Uniqueness is guaranteed by the UUID generation process.
     *
     * @return string The UUID slug.
     */
    protected function generateUniqueSlug(): string {
        return (string)Str::uuid();
    }
}
