<?php

namespace Modules\User\Observers;

use Modules\User\Entities\User;

class UserObserver
{
    /**
     * Handle the model "created" event.
     */
    public function created(User $user): void
    {
        $user->created_by = admin()?->id;
        $user->saveQuietly();
    }

    /**
     * Handle the model "updated" event.
     */
    public function updated(User $user): void
    {
        if ($user->wasChanged('picture')) {
            destroy_asset($user->getOriginal('picture'));
        }
    }

    /**
     * Handle the model "deleted" event.
     */
    public function deleted(User $user): void
    {
        $user->updateQuietly([
            'is_active' => false,
            'deleted_by' => admin()?->id,
        ]);
    }

    /**
     * Handle the model "restored" event.
     */
    public function restored(User $user): void
    {
        $user->updateQuietly([
            'deleted_by' => null,
        ]);
    }

    /**
     * Handle the model "force deleted" event.
     */
    public function forceDeleted(User $user): void
    {
        destroy_asset($user->getOriginal('picture'));
    }
}
