<?php

namespace App\Models\Concerns;

use App\Tenancy\TenantManager;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Models\Concerns\LogsActivity;
use Spatie\Activitylog\Support\LogOptions;

/**
 * Adds Spatie ActivityLog with sensible defaults + auto-fills company_id
 * on every activity row so the audit trail stays tenant-scoped.
 *
 * Use on tenant models you want audited (Client, Vehicle, WorkOrder, ...).
 */
trait Auditable
{
    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontLogEmptyChanges()
            ->setDescriptionForEvent(fn (string $event) => match ($event) {
                'created' => 'creat',
                'updated' => 'modificat',
                'deleted' => 'șters',
                'restored' => 'restaurat',
                default => $event,
            });
    }

    public function tapActivity(Activity $activity, string $eventName): void
    {
        // Auto-attach company_id if available.
        $tenantId = app(TenantManager::class)->currentId() ?: ($this->company_id ?? null);
        if ($tenantId) {
            $activity->company_id = $tenantId;
        }
        // Auto-attach causer if logged in.
        if (auth()->check() && ! $activity->causer_id) {
            $activity->causer_type = get_class(auth()->user());
            $activity->causer_id = auth()->id();
        }
    }
}
