<?php

namespace App\Models\Concerns;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

trait HasPublicUuid
{
    protected static function bootHasPublicUuid()
    {
        static::creating(function ($model) {
            if (method_exists($model, 'getTable') && Schema::hasColumn($model->getTable(), 'uuid') && empty($model->uuid)) {
                $model->uuid = (string) Str::uuid();
            }
        });
    }

    public function getRouteKeyName()
    {
        return Schema::hasColumn($this->getTable(), 'uuid') ? 'uuid' : $this->getKeyName();
    }

    public function scopeWherePublicKey($query, $key)
    {
        if (Schema::hasColumn($this->getTable(), 'uuid')) {
            $query->where('uuid', $key);
            if (is_numeric($key)) {
                $query->orWhere($this->getKeyName(), $key);
            }
            return $query;
        }

        return $query->where($this->getKeyName(), $key);
    }

    public function publicKey()
    {
        return $this->uuid ?: $this->getKey();
    }
}
