<?php

namespace App\Http\Middleware;

use App\Models\ActivityLog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class LogUserActivity
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        if (!auth()->check()) {
            return $response;
        }

        try {
            ActivityLog::create([
                'user_id' => auth()->id(),
                'method' => $request->method(),
                'path' => $request->path(),
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'payload' => $this->safePayload($request),
                'response_status' => $response->getStatusCode(),
                'created_at' => now(),
            ]);
        } catch (\Throwable $exception) {
            // Avoid breaking API/web flow due to logging failure.
        }

        return $response;
    }

    private function safePayload(Request $request): array
    {
        $input = $request->except(['password', 'password_confirmation']);

        foreach (['token', 'authorization', 'sms_panel_api_key'] as $sensitiveKey) {
            if (array_key_exists($sensitiveKey, $input)) {
                $input[$sensitiveKey] = '***';
            }
        }

        return $input;
    }
}
