<?php

namespace Modules\User\Http\Controllers\Api\Auth;

use App\Api\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Jason\Api\Api;
use Modules\User\Events\UserLoginSuccess;
use Modules\User\Http\Requests\LoginRequest;
use Modules\User\Models\User;

class LoginController extends Controller
{

    /**
     * Notes   : 用户名密码登录
     *
     * @Date   : 2021/3/11 5:03 下午
     * @Author : <Jason.C>
     * @param  LoginRequest  $request
     * @return JsonResponse
     */
    public function index(LoginRequest $request): JsonResponse
    {
        $credentials = [
            'username' => $request->username,
            'password' => $request->password,
        ];

        $token = Api::attempt($credentials);

        if ($token) {
            $user = User::where('username', $request->username)->first();
            event(new UserLoginSuccess($user, $request, '账号密码'));

            return $this->success([
                'access_token' => $token,
                'token_type'   => 'Bearer',
            ]);
        } else {
            return $this->failed('用户名或密码错误');
        }
    }

    /**
     * Notes   : 退出登录，撤销所有令牌，这个需要配合 api:^5.0 使用
     *
     * @Date   : 2021/9/22 11:07 上午
     * @Author : <Jason.C>
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        $user = Api::user();

        if ($user) {
            $user->tokens()->delete();
        }

        return $this->success('');
    }

}
