<?php
namespace App\Services;

use App\Models\AuditLog;
use Illuminate\Database\Eloquent\Model;

final class AuditService
{
    public function record(string $action,Model $model,array $old=[],array $new=[]): void
    {
        AuditLog::create([
            'user_id'=>auth()->id(),
            'action'=>$action,
            'auditable_type'=>$model->getMorphClass(),
            'auditable_id'=>$model->getKey(),
            'old_values'=>$this->scrub($old),
            'new_values'=>$this->scrub($new),
            'ip'=>request()?->ip(),
            'user_agent'=>substr((string)request()?->userAgent(),0,1000),
            'created_at'=>now(),
        ]);
    }

    private function scrub(array $values): array
    {
        foreach($values as $key=>$value){
            if(in_array(strtolower((string)$key),['password','password_confirmation','current_password','code','sender_id_number','recipient_id_number','token'],true)){
                $values[$key]='[REDACTED]';
            } elseif(is_array($value)) {
                $values[$key]=$this->scrub($value);
            }
        }
        return $values;
    }
}
