<?php

namespace Daylight\Core\Livewire\Auth;

use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Livewire\Component;

class TwoFactorChallenge extends Component
{
    public string $code = '';

    public string $recoveryCode = '';

    public bool $usingRecoveryCode = false;

    public function mount(): void
    {
        if (! session()->has('two_factor_user_id')) {
            $this->redirect(translatedRoute('login'));
        }
    }

    public function verify(): mixed
    {
        $userId = session('two_factor_user_id');

        if (! $userId) {
            return $this->redirect(translatedRoute('login'));
        }

        $userModel = config('auth.providers.users.model');
        $user = $userModel::find($userId);

        if (! $user) {
            session()->forget(['two_factor_user_id', 'two_factor_remember']);

            return $this->redirect(translatedRoute('login'));
        }

        if ($this->usingRecoveryCode) {
            if (! $user->verifyRecoveryCode($this->recoveryCode)) {
                $this->addError('recoveryCode', __('daylight::auth.two_factor.invalid_recovery_code'));

                return null;
            }
        } else {
            if (! $user->verifyTwoFactorCode($this->code)) {
                $this->addError('code', __('daylight::auth.two_factor.invalid_code'));

                return null;
            }
        }

        // Complete login
        Auth::login($user, session('two_factor_remember', false));
        session()->regenerate();
        session()->forget(['two_factor_user_id', 'two_factor_remember']);
        session(['two_factor_authenticated' => true]);

        return redirect()->intended(translatedRoute('account.index', absolute: false));
    }

    public function toggleRecoveryCode(): void
    {
        $this->usingRecoveryCode = ! $this->usingRecoveryCode;
        $this->reset(['code', 'recoveryCode']);
        $this->resetValidation();
    }

    public function render(): View
    {
        return view('daylight::livewire.auth.two-factor-challenge');
    }
}
