<?php

namespace App\Observers;

use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

class GlobalActivityObserver
{
    /**
     * 🚫 Поля, которые НИКОГДА не логируем
     */
    private array $ignoredFields = [
        'created_at',
        'updated_at',
        'deleted_at',
        'remember_token',
        'email_verified_at',
        'api_token',
        'token',
        'password',
    ];

    public function created(Model $model): void
    {
        if (!$this->shouldLog($model)) return;

        $this->log(
            'created',
            $model,
            [],
            $this->clean($model->toArray())
        );
    }

    public function updated(Model $model): void
    {
        if (!$this->shouldLog($model)) return;

        $before = $this->clean($model->getOriginal());
        $after  = $this->clean($model->getChanges());

        // ❗ если нет реальных изменений — не логируем
        if (empty($after)) return;

        $this->log('updated', $model, $before, $after);
    }

    public function deleted(Model $model): void
    {
        if (!$this->shouldLog($model)) return;

        $this->log(
            'deleted',
            $model,
            $this->clean($model->getOriginal()),
            []
        );
    }

    /**
     * 📌 Проверка: логируем ли модель
     */
    private function shouldLog(Model $model): bool
    {
        return in_array(
            get_class($model),
            config('activity-log.enabled_models', [])
        );
    }

    /**
     * 🧼 Чистим данные от мусора
     */
    private function clean(array $data): array
    {
        return collect($data)
            ->except($this->ignoredFields)
            ->filter(fn ($value) => !is_null($value))
            ->toArray();
    }

    /**
     * 🧠 Запись лога
     */
    private function log(
        string $action,
        Model $model,
        array $before = [],
        array $after = []
    ): void {
        ActivityLog::create([
            'user_id'    => Auth::id(),
            'action'     => $action,
            'model_type' => get_class($model),
            'model_id'   => $model->getKey(),
            'before'     => !empty($before) ? $before : null,
            'after'      => !empty($after) ? $after : null,
            'ip'         => Request::ip(),
            'user_agent' => Request::userAgent(),
        ]);
    }
}
