package com.evobms.project.iot.service;

import com.evobms.framework.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

/**
 * 设备令牌服务：管理 token 与设备SN 的映射
 */
@Service
public class IotDeviceTokenService {

    @Autowired
    private RedisCache redisCache;

    @Value("${iot.token.ttlSeconds:86400}")
    private int ttlSeconds;

    private static final String KEY_PREFIX = "iot:device:token:";

    /**
     * 为设备SN签发令牌，并缓存映射关系（带有效期）
     */
    public String issueTokenForSn(String sn) {
        String token = generateHexToken64();
        String key = KEY_PREFIX + token;
        redisCache.setCacheObject(key, sn, ttlSeconds, TimeUnit.SECONDS);
        return token;
    }

    /**
     * 根据令牌解析设备SN
     */
    public String getSnByToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        String key = KEY_PREFIX + token;
        return redisCache.getCacheObject(key);
    }

    private static String generateHexToken64() {
        byte[] bytes = new byte[32];
        new SecureRandom().nextBytes(bytes);
        StringBuilder sb = new StringBuilder(64);
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}