<?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 = ['abcde' => 111, 'role' => '问诊人', 'id' => $userId];

        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(['miniapp_openid', $credentials['openid']]);
            $token = auth('api')->claims(['role' => '问诊人'])->fromUser($user);
            // $data = $this->respondWithToken($token)->original;
            $data = ['token' => $token];

            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,
        ]);
    }
}
