package com.emotion.service.impl;

import com.emotion.dto.response.UserInfoResponse;
import com.emotion.exception.TokenException;
import com.emotion.service.AuthService;
import com.emotion.service.TokenService;
import com.emotion.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 令牌服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-23
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private AuthService authService;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public UserInfoResponse getUserInfoByToken(HttpServletRequest request) {
        String userId = validateTokenAndGetUserId(request);
        return authService.getCurrentUserInfo(userId);
    }

    @Override
    public String getUsernameByToken(HttpServletRequest request) {
        String token = tokenUtil.extractToken(request);
        if (!tokenUtil.isValidToken(token)) {
            throw new TokenException("未提供访问令牌");
        }

        if (!authService.validateToken(token)) {
            throw new TokenException("访问令牌无效或已过期");
        }

        String username = authService.getUsernameFromToken(token);
        if (username == null) {
            throw new TokenException("访问令牌无效");
        }

        return username;
    }

    @Override
    public String validateTokenAndGetUserId(HttpServletRequest request) {
        String token = tokenUtil.extractToken(request);
        if (!tokenUtil.isValidToken(token)) {
            throw new TokenException("未提供访问令牌");
        }

        if (!authService.validateToken(token)) {
            throw new TokenException("访问令牌无效或已过期");
        }

        String userId = authService.getUserIdFromToken(token);
        if (userId == null) {
            throw new TokenException("访问令牌无效");
        }

        return userId;
    }
}