package org.lingniu.sdk.model.token;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * Refresh Token 信息
 * 存储在 Redis Hash 结构中
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RefreshTokenInfo {
    private String tokenValue;
    
    /**
     * 用户名
     */
    private String username;

    
    /**
     * 创建时间
     */
    private Instant createdAt;
    
    /**
     * 最后使用时间
     */
    private Instant lastUsedAt;
    
    /**
     * 过期时间
     */
    private Instant expiresAt;

    /**
     * 对应accessToken
     */
    private String accessToken;
    /**
     * 关联的Access Token数量（用于统计）
     */
    private int accessTokenCount;
    
    /**
     * 使用次数
     */
    private int usageCount;
    

    
    /**
     * 附加数据（JSON格式）
     */
    private String additionalInfo;

    private String clientRegistrationId;

    
    /**
     * 检查Refresh Token是否过期
     */
    public boolean isExpired() {
        return expiresAt != null && Instant.now().isAfter(expiresAt);
    }
    
    /**
     * 检查Refresh Token是否有效
     */
    public boolean isValid() {
        return !isExpired();
    }
    
    /**
     * 获取剩余有效时间（秒）
     */
    public long getRemainingSeconds() {
        if (expiresAt == null) {
            return 0;
        }
        Instant now = Instant.now();
        if (now.isAfter(expiresAt)) {
            return 0;
        }
        return expiresAt.getEpochSecond() - now.getEpochSecond();
    }
    
    /**
     * 获取活跃天数（创建到现在）
     */
    public long getActiveDays() {
        if (createdAt == null) {
            return 0;
        }
        Instant end = Instant.now();
        long seconds = end.getEpochSecond() - createdAt.getEpochSecond();
        return seconds / (24 * 3600);
    }
    
    /**
     * 获取闲置天数（最后使用到现在）
     */
    public long getIdleDays() {
        if (lastUsedAt == null) {
            return getActiveDays();
        }
        Instant now = Instant.now();
        long seconds = now.getEpochSecond() - lastUsedAt.getEpochSecond();
        return seconds / (24 * 3600);
    }
    
    /**
     * 增加使用计数
     */
    public void incrementUsage() {
        this.usageCount++;
        this.lastUsedAt = Instant.now();
    }

    public void incrementAccessTokenUsage(String accessToken) {
        this.accessTokenCount++;
        this.accessToken = accessToken;
    }

    
    /**
     * 转换为Map，便于Redis存储
     */
    public Map<String, String> toMap() {
        Map<String, String> hash = new HashMap<>();
        hash.put("username", username != null ? username : "");
        hash.put("tokenValue", tokenValue != null ? tokenValue : "");
        hash.put("accessToken", accessToken != null ? accessToken : "");
        hash.put("createdAt", createdAt != null ? createdAt.toString() : "");
        hash.put("lastUsedAt", lastUsedAt != null ? lastUsedAt.toString() : "");
        hash.put("expiresAt", expiresAt != null ? expiresAt.toString() : "");
        hash.put("accessTokenCount", Integer.toString(accessTokenCount));
        hash.put("usageCount", Integer.toString(usageCount));
        hash.put("clientRegistrationId", clientRegistrationId);
        hash.put("additionalInfo", additionalInfo != null ? additionalInfo : "");
        
        return hash;
    }
    public Map<String, String> toUpdateMap() {
        Map<String, String> hash = new HashMap<>();
        hash.put("lastUsedAt", lastUsedAt != null ? lastUsedAt.toString() : "");
        hash.put("accessTokenCount", Integer.toString(accessTokenCount));
        hash.put("accessToken", accessToken != null ? accessToken : "");
        hash.put("usageCount", Integer.toString(usageCount));
        return hash;
    }
    
    /**
     * 从Redis Hash创建RefreshTokenInfo
     */
    public static RefreshTokenInfo fromMap(Map<String, Object> hash) {
        if (hash == null || hash.isEmpty()) {
            return null;
        }
        
        RefreshTokenInfoBuilder builder = RefreshTokenInfo.builder();
        builder.username((String) hash.getOrDefault("username", ""));
        builder.accessToken((String) hash.getOrDefault("accessToken", ""));
        builder.tokenValue((String) hash.getOrDefault("tokenValue", ""));
        builder.clientRegistrationId((String) hash.getOrDefault("clientRegistrationId", ""));

        // 处理时间字段
        String createdAtStr = (String)hash.get("createdAt");
        if (createdAtStr != null && !createdAtStr.isEmpty()) {
            try {
                builder.createdAt(Instant.parse(createdAtStr));
            } catch (Exception e) {
                // 解析失败，使用当前时间
                builder.createdAt(Instant.now());
            }
        }
        
        String lastUsedAtStr = (String)hash.get("lastUsedAt");
        if (lastUsedAtStr != null && !lastUsedAtStr.isEmpty()) {
            try {
                builder.lastUsedAt(Instant.parse(lastUsedAtStr));
            } catch (Exception e) {
                // 解析失败，忽略
            }
        }
        
        String expiresAtStr = (String)hash.get("expiresAt");
        if (expiresAtStr != null && !expiresAtStr.isEmpty()) {
            try {
                builder.expiresAt(Instant.parse(expiresAtStr));
            } catch (Exception e) {
                // 解析失败，忽略
            }
        }
        
        // 处理数值字段
        String accessTokenCountStr = (String)hash.get("accessTokenCount");
        if (accessTokenCountStr != null && !accessTokenCountStr.isEmpty()) {
            try {
                builder.accessTokenCount(Integer.parseInt(accessTokenCountStr));
            } catch (NumberFormatException e) {
                builder.accessTokenCount(0);
            }
        }
        
        String usageCountStr = (String)hash.get("usageCount");
        if (usageCountStr != null && !usageCountStr.isEmpty()) {
            try {
                builder.usageCount(Integer.parseInt(usageCountStr));
            } catch (NumberFormatException e) {
                builder.usageCount(0);
            }
        }
        
        return builder.build();
    }
}