package com.lingyue.auth.service;

import com.lingyue.auth.entity.Session;
import com.lingyue.auth.repository.SessionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Token管理服务
 */
@Service
@RequiredArgsConstructor
public class TokenService {
    
    private final SessionRepository sessionRepository;
    
    /**
     * 验证Token是否有效
     */
    public boolean validateToken(String token) {
        String tokenHash = hashToken(token);
        Session session = sessionRepository.findByTokenHash(tokenHash);
        return session != null;
    }
    
    /**
     * 根据Token获取会话
     */
    public Session getSessionByToken(String token) {
        String tokenHash = hashToken(token);
        return sessionRepository.findByTokenHash(tokenHash);
    }
    
    /**
     * 删除会话
     */
    @Transactional
    public void deleteSession(String token) {
        String tokenHash = hashToken(token);
        Session session = sessionRepository.findByTokenHash(tokenHash);
        if (session != null) {
            sessionRepository.deleteById(session.getId());
        }
    }
    
    /**
     * 哈希Token（用于存储）
     */
    private String hashToken(String token) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(token.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("Failed to hash token", e);
        }
    }
}

