<?php

namespace App\Http\Middleware;

use App\Services\OperationCounterService;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CountOperation
{
    public function __construct(private readonly OperationCounterService $operationCounterService)
    {
    }

    public function handle(Request $request, Closure $next, string $mode = 'action'): Response|RedirectResponse
    {
        $response = $next($request);

        if ($this->shouldCount($request, $response, $mode)) {
            $this->operationCounterService->increment();
        }

        return $response;
    }

    private function shouldCount(Request $request, Response|RedirectResponse $response, string $mode): bool
    {
        if ($response->getStatusCode() >= 400) {
            return false;
        }

        if ($mode === 'page') {
            return true;
        }

        if (! $request->hasSession()) {
            return true;
        }

        if ($request->session()->has('errors')) {
            return false;
        }

        if ($request->session()->has('warning') || $request->session()->has('error')) {
            return false;
        }

        return true;
    }
}