<?php

namespace App\Services;

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

class AuditService
{
    public static function record(string $action, ?Model $model = null, array $before = [], array $after = [], ?int $branchId = null): AuditLog
    {
        $request = request();

        return AuditLog::create([
            'user_id' => auth()->id(),
            'branch_id' => $branchId ?? auth()->user()?->primary_branch_id,
            'action' => $action,
            'auditable_type' => $model ? $model::class : null,
            'auditable_id' => $model?->getKey(),
            'before' => $before ?: null,
            'after' => $after ?: null,
            'ip_address' => $request?->ip(),
            'user_agent' => $request?->userAgent(),
        ]);
    }
}
