<?php  

namespace App\Admin\UserAdmin;

use App\Exceptions\BadPasswordException;
use App\JwtAuth\JwtCustomAuth;
use App\Models\Admin\AdminUser;
use Exception;
use Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserAdminService extends JwtCustomAuth
{
    public function makeLogin($request){
        
        $email = $request->email;
        $password = $request->password;
        $user = new UserAdminGetter();
        $userData = $user->getUserByEmail($email);
        if(!Hash::check($password,$userData->password)) throw new BadPasswordException("Contraseña incorrecta");
        $claims = [
            'user' => $userData->id,
            'email' => $userData->email
        ];
        $token = null;
        
        if (!$token = Auth::guard('admin')->attempt(request(['email', 'password']))) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
        return $token;
    }

    public function newUser($request){
        if($request->password !== $request->password_verify) throw new BadPasswordException("Las contraseñas no  coinciden", 1);

        AdminUser::create([
            'user' => $request->user_name,
            'email' => $request->email,
            'password' =>  Hash::make($request->password),
            'created_by' => 0,
            'is_active' => 1
        ]);
        
    }
    public static function test(){
        return response()->json(auth('admin')->user());
    }
    protected function respondWithToken($token)
    {
        return [
            'token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('admin')->factory()->getTTL() * 60
        ];
    }
}
