<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\MailSettings;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
use Throwable;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $mailSettings = app(MailSettings::class);

        try {
            event(new Registered($user));
        } catch (Throwable $exception) {
            report($exception);

            Auth::login($user);

            return redirect(route('verification.notice', absolute: false))
                ->with('status', 'verification-code-send-failed')
                ->with('verification_send_error', $mailSettings->deliveryFailureMessage(
                    $exception,
                    'Your account was created, but we could not email the verification code.',
                ));
        }

        Auth::login($user);

        $redirect = redirect(route('verification.notice', absolute: false));

        if ($mailSettings->isLogOnlyDriver()) {
            return $redirect
                ->with('status', 'verification-code-send-failed')
                ->with('verification_send_error', $mailSettings->logOnlyDeliveryMessage(
                    'Your account was created and a verification code was generated, but no inbox email was sent.',
                ));
        }

        return $redirect;
    }
}
