<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Illuminate\Http\Request;

class ConditionalValidateCsrfToken extends ValidateCsrfToken
{
    public function handle($request, Closure $next): mixed
    {
        if ($this->shouldBypassForTesting()) {
            return $next($request);
        }

        if ($request instanceof Request && $request->attributes->get('skinbase.session_skipped') === true) {
            return $next($request);
        }

        return parent::handle($request, $next);
    }

    private function shouldBypassForTesting(): bool
    {
        return app()->runningUnitTests()
            || app()->environment('testing')
            || defined('PHPUNIT_COMPOSER_INSTALL')
            || defined('__PHPUNIT_PHAR__');
    }
}