<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\Vrm\TokenService;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VerifyEmailCodeController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'verification_code' => ['required', 'digits:8'],
        ]);

        $user = $request->user();
        if (! $user) {
            return redirect()->route('login');
        }

        $token = app(TokenService::class)->verifyToken(
            token: $validated['verification_code'],
            type: 'email_verification',
            name: 'verify_account',
            userId: (int) $user->id,
            destroyOnUse: true,
        );

        if (! $token) {
            return back()->withErrors([
                'verification_code' => __('The verification code is invalid or expired.'),
            ]);
        }

        if (! $user->hasVerifiedEmail()) {
            $user->forceFill([
                'email_verified_at' => now(),
                'phone_verified_at' => now(),
                'is_active' => true,
            ])->save();

            event(new Verified($user));
        }

        Auth::login($user);

        return redirect()->route('member.dashboard')->with('status', 'verification-code-verified');
    }
}
