<?php

namespace App\Http\Strategies\PasswordRecovery;

use App\Http\Enums\AuthStrategies;
use App\Http\Repositories\UserRepository;
use App\Http\Actions\ActivationCodeAction;
use App\Http\Repositories\PasswordRecoveryTokenRepository;

class PhoneStrategy implements IPasswordRecoveryStrategy
{
    public function forgot($identifier)
    {
        $user = (new UserRepository())->userByVerifiedPhone($identifier);

        $activation_code = 1234; // ActivationCodeAction::action();

        (new PasswordRecoveryTokenRepository)->create($user->phone, AuthStrategies::Phone->value, $activation_code);

        // TODO: Send verification code via SMS
    }

    public function check($identifier, $code)
    {
        $user = (new UserRepository())->userByVerifiedPhone($identifier);

        if (!(new PasswordRecoveryTokenRepository)->verify($identifier, AuthStrategies::Phone->value, $code))
            respond()->unauthorized(__('Code is incorrect'))->throwResponse();

        return $user;
    }

    public function reset($identifier, $code, $password)
    {
        $user = (new UserRepository())->userByVerifiedPhone($identifier);

        if (!(new PasswordRecoveryTokenRepository)->reset($identifier, AuthStrategies::Phone->value, $code))
            respond()->unauthorized(__('Code is incorrect'))->throwResponse();

            $user->update([
            'password' => $password,
        ]);

        return $user;
    }
}
