<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;

class VerifyEmailController extends Controller
{
    /**
     * Mark the authenticated user's email address as verified.
     *
     * NOTE: The `absolute: true` parameter below is necessary for proper
     * redirect behavior when the application is deployed under a URL subpath
     * (e.g., /php85/{user}/) rather than at the domain root. This ensures
     * the redirect URL includes the full path context and prevents redirect
     * loops or incorrect navigation.
     *
     * This change is orthogonal to the creative wizard feature, but is
     * required for reliable email verification across all deployment
     * configurations (subdirectory dev, domain root staging/prod).
     */
    public function __invoke(EmailVerificationRequest $request): RedirectResponse
    {
        if ($request->user()->hasVerifiedEmail()) {
            return redirect()->intended(route('home', absolute: true).'?verified=1');
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect()->intended(route('home', absolute: true).'?verified=1');
    }
}
