<?php

namespace App\Observers;

use App\Core\Hook\HookBridge;
use App\Models\User;

class UserObserver
{
    public function creating(User $user): void
    {
        app(HookBridge::class)->fireAction('PreUserAdd',
            app(HookBridge::class)->buildUserContext($user));
    }

    public function created(User $user): void
    {
        app(HookBridge::class)->fireAction('UserAdd',
            app(HookBridge::class)->buildUserContext($user));
    }

    public function updated(User $user): void
    {
        $bridge = app(HookBridge::class);
        $bridge->fireAction('UserEdit', $bridge->buildUserContext($user, [
            'olddata' => $user->getOriginal(),
        ]));

        if ($user->wasChanged('password')) {
            $bridge->fireAction('UserChangePassword', [
                'user_id'  => $user->id,
                'userid'   => $user->id,
                'password' => '(redacted)',
            ]);
        }

        if ($user->wasChanged('email_verified_at') && $user->email_verified_at && ! $user->getOriginal('email_verified_at')) {
            $bridge->fireAction('UserEmailVerificationComplete', [
                'userId'  => $user->id,
                'user_id' => $user->id,
            ]);
        }
    }
}
