<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;


/**
 * JWT 认证服务
 * @package app\service
 */
class AuthService
{
    /** @var string|null JWT 密钥缓存 */
    private static $secretKey = null;
    /** @var string JWT 算法 */
    private static $algorithm = 'HS256';
    private const TOKEN_TTL_SECONDS = 7 * 86400;

     /**
     * 获取JWT密钥
     * @return string
     */
    private static function getSecretKey(): string
    {
        if (self::$secretKey !== null) {
            return self::$secretKey;
        }
        $key = env('JWT_SECRET', '');
        if ($key === '') {
            throw new \RuntimeException('JWT_SECRET is not configured in .env');
        }
        self::$secretKey = $key;
        return $key;
    }


     /**
     * 创建JWT
     * @param int $userId
     * @param int $userType
     * @return string
     */
    public static function createToken($userId, $userType = 1)
    {
        $payload = [
            'iss' => 'niushui.com',
            'aud' => 'niushui.com',
            'iat' => time(),
            'nbf' => time(),
            'exp' => time() + self::TOKEN_TTL_SECONDS,
            'uid' => $userId,
            'type' => $userType
        ];

        return JWT::encode($payload, self::getSecretKey(), self::$algorithm);
    }

     /**
     * 验证JWT
     * @param string $tokenString
     * @return array
     */
    public static function validateToken($tokenString)
    {
        try {
            $decoded = JWT::decode($tokenString, new Key(self::getSecretKey(), self::$algorithm));
            $decodedArray = (array) $decoded;

            return [
                'ok' => true,
                'reason' => 'ok',
                'uid' => $decodedArray['uid'] ?? null,
                'type' => $decodedArray['type'] ?? 1
            ];
        } catch (ExpiredException $e) {
            return [
                'ok' => false,
                'reason' => 'expired_token',
            ];
        } catch (\Exception $e) {
            return [
                'ok' => false,
                'reason' => 'invalid_token',
            ];
        }
    }
}