<?php

namespace App\Services;

use App\Models\AuditLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

class AuditLogService
{
    /**
     * Log user or system action.
     * Supports both static and instance-based calls.
     */
    public static function log(
        string $action,
        string $module,
        string|int|null $recordId = null,
        ?array $oldValues = null,
        ?array $newValues = null
    ): AuditLog {
        return self::record($action, $module, $recordId, $oldValues, $newValues);
    }

    /**
     * Static shorthand.
     */
    public static function record(
        string $action,
        string $module,
        string|int|null $recordId = null,
        ?array $oldValues = null,
        ?array $newValues = null
    ): AuditLog {
        $user = Auth::user();

        return AuditLog::create([
            'user_id'    => $user?->id,
            'user_name'  => $user?->name ?? 'System',
            'action'     => $action,
            'module'     => $module,
            'record_id'  => $recordId ? (string)$recordId : null,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'ip_address' => Request::ip(),
            'user_agent' => Request::userAgent(),
        ]);
    }
}
