<?php

namespace App\Livewire\Auth;

use App\Models\User;
use Livewire\Component;
use App\Events\UserLoggedIn;
use App\Services\OtpService;
use App\Services\UserService;
use App\Exceptions\OtpException;
use Illuminate\Auth\Events\Login;
use Livewire\Attributes\Validate;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Session;

class LoginVerification extends Component
{
    #[Validate('required')]
    public $otpCode;

    public function loginWithPassword()
    {
        if (User::where('phone', Session::get('login_identifier'))->exists()) {
            $this->dispatch('showPasswordStep');
        } else {
            $this->dispatch('showRegisterStep');
        }
    }

    public function sendOtp()
    {
        try {
            OtpService::sendOtp(Session::get('login_identifier'));
        } catch (OtpException $exception) {
            $this->addError('identifier', $exception->getMessage());
        }
    }

    public function verifyOTP()
    {
        $this->validate();

        $result = OtpService::verifyOtp(Session::get('login_identifier'), $this->otpCode);

        if ($result == true) {
            $isUserLoggedIn = $this->registerIfNotExits(phone: Session::get('login_identifier'));
            if ($isUserLoggedIn == true) {
                return redirect()->route('user.dashboard');
            }
        }

        return $this->addError('error', __('something went wrong! please refresh the page'));
    }

    public function goBackToIdentifier()
    {
        $this->dispatch('showIdentifierStep');
    }

    public function render()
    {
        return view('livewire.auth.login-verification');
    }

    private function registerIfNotExits($phone): bool
    {
        $user = UserService::registerIfNotExist($phone);

        Auth::login($user);

        event(new UserLoggedIn($user));
        return true;
    }
}
