<?php

namespace App\Observers;

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

class EntityHistoryObserver
{
    public function created(Model $model): void
    {
        $this->recordHistory($model, 'created', null, $model->getAttributes());
    }

    public function updated(Model $model): void
    {
        $changes = $model->getChanges();
        $original = array_intersect_key($model->getOriginal(), $changes);

        $this->recordHistory($model, 'updated', $original, $changes);
    }

    public function deleted(Model $model): void
    {
        $this->recordHistory($model, 'deleted', $model->getAttributes(), null);
    }

    public function restored(Model $model): void
    {
        $this->recordHistory($model, 'restored', null, $model->getAttributes());
    }

    private function recordHistory(Model $model, string $action, ?array $before, ?array $after): void
    {
        // Avoid infinite loop if EntityHistory itself changes
        if ($model instanceof EntityHistory) {
            return;
        }

        try {
            // Skip saat tabel belum ada (awal migrate) atau DB belum siap
            if (!\Illuminate\Support\Facades\Schema::hasTable('entity_histories')) {
                return;
            }

            EntityHistory::create([
                'user_id' => Auth::id(),
                'entity_type' => get_class($model),
                'entity_id' => $model->getKey(),
                'action' => $action,
                'before_values' => $before,
                'after_values' => $after,
            ]);
        } catch (\Throwable $e) {
            logger()->warning('[EntityHistoryObserver] '.$e->getMessage());
        }
    }
}
