<?php

namespace App\Service;

use App\Exceptions\UserException;
use App\Models\User;
use Illuminate\Support\Arr;

class UserService
{
    /**
     * @param $token
     * @return array
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ];
    }

    public function login(array $data)
    {
        $credentials = Arr::only($data, ['email', 'password']);
        $email = $credentials['email'] ?? '';
        $password = $credentials['password'] ?? '';
        $Users = User::where('email', $email)->first();
        if (blank($Users)) {
            throw new UserException(1, '账号不存在');
        }
        if ($password != $Users->password) {
            throw new UserException(1, '密码错误');
        }
        # 登录
        $token = auth('api')->login($Users);
        return $this->respondWithToken($token);
    }

    public function logout()
    {
        return auth('api')->logout();
    }

}


