<?php

namespace App\Http\Middleware;

use App\Services\Auth\PasswordPolicyService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class PasswordExpiryMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {
            $user = Auth::user();

            // Skip for specific routes to avoid infinite loops
            if ($request->is('profile/password*') || $request->is('logout')) {
                return $next($request);
            }

            if (PasswordPolicyService::isPasswordExpired($user)) {
                return redirect()->route('profile.edit')
                    ->with('warning', __('Your password has expired. Please update it to continue using the application.'));
            }
        }

        return $next($request);
    }
}
