<?php

namespace App\Filament\Student\Pages\Auth;

use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Filament\Auth\Events\Registered;
use Filament\Auth\Http\Responses\Contracts\RegistrationResponse;
use Filament\Auth\Pages\Register as BaseRegister;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\UserRegisteredMail;

class Register extends BaseRegister
{
    public function register(): ?RegistrationResponse
    {
        try {
            $this->rateLimit(2);
        } catch (TooManyRequestsException $exception) {
            $this->getRateLimitExceededNotification($exception)?->send();

            return null;
        }

        $user = $this->wrapInDatabaseTransaction(function () {
            $this->callHook('beforeRegister');

            $data = $this->form->getState();

            $user = $this->handleRegistration($data);

            $this->form->model($user)->saveRelationships();

            $this->callHook('afterRegister');

            return $user;
        });

        event(new Registered($user));

        // Disable auto-login
        // $this->sendEmailVerificationNotification($user);
        // Filament::auth()->login($user);
        // session()->regenerate();

        Mail::to($user->email)->queue(new UserRegisteredMail(
            $user->name,
            route('filament.student.pages.dashboard')
        ));

        // Custom Notification
        Notification::make()
            ->title('Registration Successful')
            ->body("Your application is provisionally Submitted. Kindly Login with your email id {$user->email} as username and password used for registration")
            ->success()
            ->persistent()
            ->send();

        // Redirect to Login
        return app(RegistrationResponse::class);
    }

    protected function handleRegistration(array $data): \App\Models\User
    {
        /** @var \App\Models\User $user */
        $user = $this->getUserModel()::create($data);

        // Assign student role
        $user->assignRole('student');

        return $user;
    }
}
