<?php

declare(strict_types=1);

namespace App\Listeners;

use Hyperf\Database\Model\Events\Saving;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Context\ApplicationContext;
use Hyperf\Stringable\Str;
use Hypervel\Support\Facades\Auth;

#[Listener]
class ModelSavingListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            Saving::class,
        ];
    }

    public function process(object $event): void
    {
        if (! $event instanceof Saving) {
            return;
        }

        $model = $event->getModel();

        // Access container services (like auth)
        // $container = ApplicationContext::getContainer();
        // $auth = $container->get(\Hyperf\Auth\Contract\AuthInterface::class);
        // $userId = $auth->user()?->getId();
        $userId =Auth::id();

        if (! $model->exists) {
            if ($model->isFillable('hashkey') || isset($model->hashkey)) {
                $model->hashkey = Str::uuid()->toString() . Str::random(100);
            }
            if ($model->isFillable('created_by') || isset($model->created_by)) {
                $model->created_by = $userId ?? null;
            }
        }

        if ($model->isFillable('updated_by') || isset($model->updated_by)) {
            $model->updated_by = $userId ?? null;
        }
    }
}
