<?php

namespace App\Services;

use App\Models\User;
use Firebase\JWT\JWT;
use Exception;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Cache;

class JwtService
{
// 你的密钥，建议保存在环境变量中
    private $secretKey;
    private $exp;

    public function __construct()
    {
        $this->secretKey = config('app.jwt_secret');
        $this->exp = config('app.jwt_exp');
    }

// 生成 JWT
    public function generateToken($user)
    {
        $issuedAt = time();
        $expirationTime = $issuedAt + $this->exp;
        $payload = [
            'iat' => $issuedAt,
            'exp' => $expirationTime,
            'sub' => $user->id,
            'user_id' => $user->id,
        ];
        $token = JWT::encode($payload, $this->secretKey, 'HS256');
        if ($user instanceof User) {
            Cache::put("user_{$user->id}_jwt", $token, $this->exp);
        }
        return $token;
    }

    // 验证 JWT
    public function validateToken($token)
    {
        try {
            $decoded = JWT::decode($token, new Key($this->secretKey, 'HS256'));
            return (object)$decoded; // 返回解码后的 JWT 数据
        } catch (Exception $e) {
            return null; // Token 无效或过期
        }
    }

}
