<?php

namespace App\Services;

use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AuditLogService
{
    public function record(string $action, ?Model $subject = null, array $metadata = [], ?User $actor = null, ?Request $request = null): AuditLog
    {
        $request ??= request();
        $actor ??= $request?->user();

        return AuditLog::create([
            'uuid' => (string) Str::uuid(),
            'actor_user_id' => $actor?->id,
            'action' => $action,
            'subject_type' => $subject ? $subject::class : null,
            'subject_id' => $subject?->getKey(),
            'ip_address' => $request?->ip(),
            'user_agent' => $request ? mb_substr((string) $request->userAgent(), 0, 500) : null,
            'metadata' => $metadata ?: null,
        ]);
    }
}
