<?php
namespace App\Models\Trait;

use App\Services\IdHasherService;

trait HasCode
{
    public static function bootHasCode()
    {
        // static::created(function ($model) {
        //     if (!$model->code) {
        //         $model->code = IdHasherService::encode($model->id);
        //         $model->saveQuietly();
        //     }
        // });
        static::created(function ($model) {
            if (!$model->code) {
                $code = IdHasherService::encode($model->id);
                $model->newQueryWithoutScopes()
                      ->where('id', $model->id)
                      ->update(['code' => $code]);
        
                // Optionally, sync in-memory model
                $model->code = $code;
            }
        });
        
        static::updated(function ($model) {
            if (!$model->code) {
                $model->code = IdHasherService::encode($model->id);
                $model->saveQuietly();
            }
        });
    }

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