<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Resources\Auth\EmailAlreadyVerifiedResource;
use App\Http\Resources\Auth\EmailVerifiedResource;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;

class VerifyEmailController extends Controller
{
    /**
     * Mark the authenticated user's email address as verified.
     */
    public function __invoke(EmailVerificationRequest $request): JsonResponse|RedirectResponse
    {
        if ($request->user()->hasVerifiedEmail()) {
            return (new EmailAlreadyVerifiedResource($request))->response();

            return redirect()->intended(
                config('app.frontend_url').'/auth'
            );
        }

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

        return (new EmailVerifiedResource($request))->response();

        return redirect()->intended(
            config('app.frontend_url').'/auth'
        );
    }
}
