<?php

namespace App\Services;

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

class AuditLogService
{
    public function record(string $action, ?Model $model = null, array $old = [], array $new = [], ?int $userId = null): AuditLog
    {
        $hidden = ['password', 'remember_token'];

        return AuditLog::query()->create([
            'user_id' => $userId ?? Auth::id(),
            'action' => $action,
            'model_type' => $model ? $model::class : null,
            'model_id' => $model?->getKey(),
            'old_values' => $this->except($old, $hidden),
            'new_values' => $this->except($new, $hidden),
            'ip_address' => Request::ip(),
            'user_agent' => substr((string) Request::userAgent(), 0, 1000),
        ]);
    }

    protected function except(array $values, array $hidden): array
    {
        return collect($values)->except($hidden)->toArray();
    }
}
