<?php

namespace App\Services\Audit;

use App\Models\Audit\AuditLog;

class AuditLogger
{
    /**
     * 감사 로그 기록
     */
    public function log(
        int $tenantId,
        string $targetType,
        ?int $targetId,
        string $action,
        ?array $before = null,
        ?array $after = null
    ): void {
        try {
            $request = request();
            $actorId = optional(auth()->user())->id ?? null;
            $ip = $request?->ip();
            $ua = $request?->userAgent();

            AuditLog::create([
                'tenant_id' => $tenantId,
                'target_type' => $targetType,
                'target_id' => $targetId,
                'action' => $action,
                'before' => $before,
                'after' => $after,
                'actor_id' => $actorId,
                'ip' => $ip,
                'ua' => $ua,
                'created_at' => now(),
            ]);
        } catch (\Throwable $e) {
            // 감사 로그 실패는 업무 흐름을 방해하지 않음
        }
    }
}
