<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUser
{
    public function handle(Request $request, Closure $next): Response
    {
        if (!$request->user()) {
            abort(403);
        }
        
        // Check if user's email is verified (skip for test emails)
        $email = $request->user()->email;
        $isTestEmail = str_contains($email, '@example.com') || 
                      str_contains($email, '@test.com') || 
                      str_contains($email, '@localhost') ||
                      str_contains($email, '@demo.com');
        
        if (!$request->user()->email_verified_at) {
            if ($isTestEmail) {
                return redirect()->route('test-email-warning');
            } else {
                return redirect()->route('verification.notice')
                    ->with('success', 'Please verify your email address before accessing your account.');
            }
        }
        
        return $next($request);
    }
}