<?php

namespace App\Models\Traits;

trait HasUidTrait
{
    /**
     * Ensure that when a model is saving, a unique ID
     * is set for the model.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public static function bootHasUidTrait(): void
    {
        //
    }

    /**
     * Initialize logic.
     *
     * @since 1.0.0
     *
     * @return void
     */
    protected function initializeHasUidTrait(): void
    {
        $this->id = $this->generateUid();
    }

    /**
     * Generates a cryptographically safe unique ID.
     *
     * @since 1.0.0
     *
     * @return string
     */
    public function generateUid(): string
    {
        $bytes = openssl_random_pseudo_bytes(env('APP_UID_BYTES', 8));
        return bin2hex($bytes);
    }
}
