<?php

namespace Modules\Event\Observers;

use Modules\Event\Entities\Event;

class EventObserver
{
    /**
     * Handle the model "created" event.
     */
    public function created(Event $event): void
    {
        $event->created_by = admin()?->id;
        $event->slug = str($event->title)->slug() . '-' . $event->id;
        $event->saveQuietly();
    }

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

        if ($event->wasChanged('banner')) {
            destroy_asset($event->getOriginal('banner'));
        }

        if ($event->wasChanged('file_path')) {
            destroy_asset($event->getOriginal('file_path'));
        }
    }

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

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

    /**
     * Handle the model "force deleted" event.
     */
    public function forceDeleted(Event $event): void
    {
        destroy_asset($event->getOriginal('thumbnail'));
        destroy_asset($event->getOriginal('banner'));
        destroy_asset($event->getOriginal('file_path'));
    }
}
