<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VerifyEmailController extends Controller
{
    public function __invoke(Request $request): RedirectResponse
    {
        // Ambil user dari parameter URL langsung (tidak butuh session)
        $user = User::findOrFail($request->route('id'));

        // Validasi signature URL
        if (!$request->hasValidSignature()) {
            return redirect()->route('login')
                ->with('error', 'Link verifikasi sudah kadaluarsa. Silakan login dan minta link baru.');
        }

        // Validasi hash
        if (!hash_equals(
            sha1($user->getEmailForVerification()),
            (string) $request->route('hash')
        )) {
            return redirect()->route('login')
                ->with('error', 'Link verifikasi tidak valid.');
        }

        // Proses verifikasi
        if (!$user->hasVerifiedEmail()) {
            $user->markEmailAsVerified();
            event(new Verified($user));
        }

        // Pastikan logout jika ada session aktif
        if (Auth::check()) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
        }

        // ✅ Langsung ke login dengan pesan sukses
        return redirect()->route('login')
            ->with('status', 'Email berhasil diverifikasi! Silakan login untuk melanjutkan.');
    }
}