<?php

namespace App\Livewire\Auth;

use App\Models\Invitation;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('components.layouts.auth')]
class Register extends Component
{
    public string $name = '';

    public string $email = '';

    public string $password = '';

    public string $password_confirmation = '';

    #[Url]
    public string $code = '';

    public ?Invitation $invitation = null;

    public bool $invitationAccepted = false;

    public function mount()
    {
        if ($this->code) {
            $this->invitation = Invitation::where('code', $this->code)->first();

            if ($this->invitation) {
                if (!$this->invitation->isPending()) {
                    $this->invitationAccepted = true;
                    return;
                }

                $this->email = $this->invitation->email;
            }
        }
    }

    /**
     * Handle an incoming registration request.
     */
    public function register(): void
    {
        if ($this->invitation && !$this->invitation->isPending()) {
            $this->addError('general', 'This invitation has already been accepted.');
            return;
        }

        $validationRules = [
            'name' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
        ];

        if ($this->invitation) {
            $validationRules['email'] = ['required', 'string', 'lowercase', 'email', 'max:255', 'in:' . $this->invitation->email];
        } else {
            $validationRules['email'] = ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:' . User::class];
        }

        $validated = $this->validate($validationRules);

        $validated['password'] = Hash::make($validated['password']);

        if ($this->invitation) {
            $validated['email'] = $this->invitation->email;
        }

        event(new Registered(($user = User::create($validated))));

        if ($this->invitation) {
            $this->invitation->accept();
        }

        Auth::login($user);

        $this->redirect(route('dashboard', absolute: false), navigate: true);
    }
}
