<?php

declare(strict_types=1);

namespace app\common\library;

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

/**
 * Agent 鉴权 JWT 工具
 */
class AgentJwt
{
    public const ALG = 'HS256';

    /**
     * 生成 JWT authtoken
     * @param array $payload agent_id, channel_id, admin_id 等
     * @param int $expire 有效期（秒）
     */
    public static function encode(array $payload, int $expire = 86400): string
    {
        $now = time();
        $payload['iat'] = $now;
        $payload['exp'] = $now + $expire;
        $secret = self::getSecret();
        return JWT::encode($payload, $secret, self::ALG);
    }

    /**
     * 解析并验证 JWT，返回 payload
     * @return array payload，失败返回空数组
     */
    public static function decode(string $token): array
    {
        if ($token === '') {
            return [];
        }
        try {
            $secret = self::getSecret();
            $decoded = JWT::decode($token, new Key($secret, self::ALG));
            return (array) $decoded;
        } catch (ExpiredException|SignatureInvalidException|\Throwable) {
            return [];
        }
    }

    /**
     * 验证 JWT 是否有效
     */
    public static function verify(string $token): bool
    {
        return !empty(self::decode($token));
    }

    private static function getSecret(): string
    {
        $secret = config('buildadmin.agent_auth.jwt_secret', '');
        if ($secret === '') {
            $secret = config('buildadmin.token.key', '');
        }
        return $secret;
    }
}
