<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends BaseApiController
{
    public function userInfo()
    {
        $userId = auth('api')->user()->id;
        $data = ['id' => $userId, 'login_type' => User::LOGIN_TYPE_USER];

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

    // 小程序静默登录，如果没有记录则生成一条
    public function login(Request $request)
    {
        $code = $request->input('code');
        $credentials = app('wechat.mini_program')->auth->session($code);
        if ($credentials['openid'] ?? '') {
            $user = User::firstOrCreate(['openid', $credentials['openid']]);
            // 追加登录类型到token里面,前端需要带在header头中 Authorization:Bearer Token
            $token = auth('api')->claims(['login_type' => User::LOGIN_TYPE_USER])->fromUser($user);
            $data = $this->respondWithToken($token)->original;

            return $this->success($data);
        } else {
            return $this->fail('登录错误~');
        }
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return response()->json(['message' => '退出成功~']);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string  $token
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
        ]);
    }
}
