<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {
            /** @var User $user */
            $user = Auth::user();

            // If user is inactive, always redirect to OTP verification
            if ($user->status === User::STATUS_INACTIVE) {
                // Allow OTP verification page and its Livewire updates
                if ($request->routeIs('otp.verify') || $request->is('livewire/update')) {
                    return $next($request);
                }

                // Redirect to OTP page for all other routes
                return redirect()->route('otp.verify');
            }
        }

        return $next($request);
    }
}
