<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\DberpDictionaryItem;
use App\Services\DberpAuditService;

final class DberpDictionaryItemObserver
{
    public function created(DberpDictionaryItem $item): void
    {
        if (! auth()->check()) {
            return;
        }

        $audit = app(DberpAuditService::class);
        $audit->log(
            'dberp.dictionary_item.created',
            $item,
            null,
            $audit->snapshot($item, $item->getFillable()),
        );
    }

    public function updated(DberpDictionaryItem $item): void
    {
        if (! auth()->check()) {
            return;
        }

        $fillable = $item->getFillable();

        if (array_intersect($fillable, array_keys($item->getChanges())) === []) {
            return;
        }

        $audit = app(DberpAuditService::class);
        $audit->log(
            'dberp.dictionary_item.updated',
            $item,
            null,
            $audit->snapshot($item, $item->getFillable()),
        );
    }

    public function deleted(DberpDictionaryItem $item): void
    {
        if (! auth()->check()) {
            return;
        }

        $audit = app(DberpAuditService::class);
        $audit->log(
            'dberp.dictionary_item.deleted',
            $item,
            $audit->snapshot($item, $item->getFillable()),
            null,
        );
    }
}
