package com.reading.platform.service.impl;

import com.reading.platform.common.security.JwtPayload;
import com.reading.platform.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Token Service 实现类 - 使用 Redis 存储 Token
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TokenServiceImpl implements TokenService {

    private final StringRedisTemplate redisTemplate;

    private static final String TOKEN_PREFIX = "token:";

    @Value("${jwt.expiration}")
    private Long tokenExpireTime;

    @Override
    public void saveToken(String token, JwtPayload payload) {
        try {
            String key = TOKEN_PREFIX + token;
            String value = payloadToString(payload);
            redisTemplate.opsForValue().set(key, value, tokenExpireTime, TimeUnit.MILLISECONDS);
            log.debug("Token saved to Redis: {}", key);
        } catch (Exception e) {
            log.warn("Failed to save token to Redis (Redis may be unavailable): {}", e.getMessage());
            // 不抛出异常，允许登录继续
        }
    }

    @Override
    public JwtPayload getToken(String token) {
        try {
            String key = TOKEN_PREFIX + token;
            String value = redisTemplate.opsForValue().get(key);
            if (value == null) {
                return null;
            }
            return stringToPayload(value);
        } catch (Exception e) {
            log.warn("Failed to get token from Redis: {}", e.getMessage());
            return null;
        }
    }

    @Override
    public void removeToken(String token) {
        try {
            String key = TOKEN_PREFIX + token;
            redisTemplate.delete(key);
            log.debug("Token removed from Redis: {}", key);
        } catch (Exception e) {
            log.warn("Failed to remove token from Redis: {}", e.getMessage());
        }
    }

    @Override
    public boolean isTokenExist(String token) {
        try {
            String key = TOKEN_PREFIX + token;
            return Boolean.TRUE.equals(redisTemplate.hasKey(key));
        } catch (Exception e) {
            log.warn("Failed to check token existence: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 将 JwtPayload 转换为字符串存储
     */
    private String payloadToString(JwtPayload payload) {
        return String.format("%s|%s|%s|%s|%s",
                payload.getUserId(),
                payload.getUsername(),
                payload.getRole(),
                payload.getTenantId() != null ? payload.getTenantId() : "",
                payload.getName() != null ? payload.getName() : "");
    }

    /**
     * 从字符串转换为 JwtPayload
     */
    private JwtPayload stringToPayload(String value) {
        String[] parts = value.split("\\|", -1);
        if (parts.length < 5) {
            return null;
        }
        return JwtPayload.builder()
                .userId(parts[0])
                .username(parts[1])
                .role(parts[2])
                .tenantId(parts[3].isEmpty() ? null : parts[3])
                .name(parts[4].isEmpty() ? null : parts[4])
                .build();
    }
}