<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class LogCsrfFailure
{
    public function handle(Request $request, Closure $next)
    {
        return $next($request);
    }

    public function terminate(Request $request, $response)
    {
        // Log CSRF-related errors (419 for mismatch, 403 for forbidden, 422 for validation errors)
        if (in_array($response->getStatusCode(), [419, 403, 422])) {
            // Check if this is likely a CSRF error by checking if it's a POST/PUT/DELETE/PATCH request
            $methodsRequiringCsrf = ['POST', 'PUT', 'DELETE', 'PATCH'];
            if (in_array($request->getMethod(), $methodsRequiringCsrf)) {
                \Log::warning('CSRF Token Mismatch / Request Failure', [
                    'method' => $request->getMethod(),
                    'path' => $request->path(),
                    'url' => $request->url(),
                    'status_code' => $response->getStatusCode(),
                    'user_id' => $request->user()?->id,
                    'has_csrf_header' => $request->header('X-CSRF-TOKEN') ? 'yes' : 'no',
                    'has_xsrf_header' => $request->header('X-XSRF-TOKEN') ? 'yes' : 'no',
                    'csrf_header_length' => strlen($request->header('X-CSRF-TOKEN') ?? ''),
                    'xsrf_header_length' => strlen($request->header('X-XSRF-TOKEN') ?? ''),
                    'has_token_field' => $request->has('_token') ? 'yes' : 'no',
                    'token_length' => strlen($request->input('_token') ?? ''),
                    'session_id' => session()->getId(),
                    'user_agent' => substr($request->userAgent() ?? '', 0, 100),
                    'cookies' => array_keys($request->cookies->all()),
                ]);
            }
        }
    }
}
