<?php

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\RegisteredUserController;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::middleware('guest')->group(function () {
    Route::get('register', [RegisteredUserController::class, 'create'])->name('register');
    Route::post('register', [RegisteredUserController::class, 'store'])
        ->middleware('throttle:5,1')          // max 5 registrations per minute per IP
        ->name('register.store');

    Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
    Route::post('login', [AuthenticatedSessionController::class, 'store'])
        ->middleware('throttle:10,1')         // max 10 login attempts per minute per IP
        ->name('login.store');
});

// Email verification
Route::middleware('auth')->group(function () {
    Route::get('email/verify', fn () => view('auth.verify-email'))
        ->name('verification.notice');

    Route::get('email/verify/{id}/{hash}', function (Request $request, $id, $hash) {
        // If the link belongs to a different account, log out and ask them to
        // sign in as the right account before clicking the link again.
        if (Auth::check() && (string) Auth::id() !== (string) $id) {
            session()->forget('impersonator_id');
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            return redirect()->route('login')
                ->with('info', 'Please log in with the account that owns this verification link, then click the link again.');
        }

        $user = Auth::user();

        // Validate the hash against the authenticated user's email
        if (! hash_equals(sha1($user->getEmailForVerification()), (string) $hash)) {
            abort(403);
        }

        if (! $user->hasVerifiedEmail()) {
            $user->markEmailAsVerified();
            event(new \Illuminate\Auth\Events\Verified($user));
        }

        return redirect('/videos')->with('verified', true);
    })->middleware('signed')->name('verification.verify');

    Route::post('email/verification-notification', function (Request $request) {
        $request->user()->sendEmailVerificationNotification();
        return back()->with('resent', true);
    })->middleware('throttle:3,1')->name('verification.send');

    Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])->name('logout');
});
