<?php

namespace App\Http\Middleware;

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

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

        // Skip for guests
        if (! $user) {
            return $next($request);
        }

        // Avoid infinite redirect loop; also skip auth verification routes
        if ($request->routeIs('legal.*', 'verification.*', 'password.*') || $request->is('logout')) {
            return $next($request);
        }

        // Check if user has agreed to current ToS and PDP versions
        if (! $user->hasAgreedToCurrentLegal('tos') || ! $user->hasAgreedToCurrentLegal('privacy')) {
            return redirect()->route('legal.re-agree');
        }

        return $next($request);
    }
}
