<?php

declare(strict_types=1);

namespace App\Controller\PunchCard\User;

use App\Controller\BaseController;
use App\Exception\BusinessException;
use app\Constants\Wechat\AuthErrorCode;
use App\Service\User\WechatAuthService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Phper666\JWTAuth\Middleware\JWTAuthDefaultSceneMiddleware;

/**
 * 微信授权处理控制器
 */
#[Controller(prefix: "kq")]
class WechatAuthController extends BaseController
{
    /**
     * 微信授权服务
     *
     * @var WechatAuthService
     */
    #[Inject]
    protected WechatAuthService $service;

    /**
     * 通过微信授权新建用户
     *
     * @return array
     */
    #[RequestMapping(path: "auth/code2OpenID", methods: "get,post")]
    public function code2OpenID() : array
    {
        $code = $this->request->input('code', '');

        if (empty($code)) {
            throw new BusinessException(AuthErrorCode::CODE_EMPTY_ERROR);
        }

        return $this->service->codeToOpenID($code);
    }

    /**
     * 刷新token
     *
     * @return array
     */
    #[Middleware(JWTAuthDefaultSceneMiddleware::class)]
    #[GetMapping(path: "auth/refresh_token")]
    public function refreshToken() : array
    {
        return $this->service->refreshToken();
    }
}