package com.backendsys.modules.common.config.security.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

@Service
public class TokenUtil {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${REDIS_LOGIN_TOKEN_PREFIX}")
    private String REDIS_LOGIN_TOKEN_PREFIX;

    public Long getUserId() {
        Claims tokenInfo = getRedisTokenInfo();
        return Convert.toLong(tokenInfo.get("user_id"));
    }

    /**
     * 获得当前系统登录用户在 Redis 中的信息 (如果想在 token 加字段，要在  JwtUtil.createSystemToken 中增加)
     * @return
     */
    public Claims getRedisTokenInfo() {
        String token = stringRedisTemplate.opsForValue().get(REDIS_LOGIN_TOKEN_PREFIX + getLoginUUID());
        if (token != null && !token.isEmpty()) {
            Claims tokenInfo = jwtUtil.extractAllClaims(token);
            return tokenInfo;
        }
        return null;
    }

    /**
     * 删除旧的登录缓存
     */
    public void deleteRedisLoginToken(String uuid) {
        stringRedisTemplate.delete(REDIS_LOGIN_TOKEN_PREFIX + (StrUtil.isNotEmpty(uuid) ? uuid : getLoginUUID()));
    }

    /**
     * 获得当前系统的 (改为 last_login_uuid) （登录用户的 UUID）
     * @return
     */
    public String getLoginUUID() {
        // 获取当前请求的 userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        String loginUUID = (principal instanceof UserDetails) ? ((UserDetails)principal).getUsername() : principal.toString();
        return loginUUID;
    }
    /**
    * 获取请求头中的 Authorization 的 Token 值
    * @param request
    * @return
    */
    public String getToken(HttpServletRequest request) {
       String authorization = request.getHeader("Authorization");
       String token = StringUtils.hasText(authorization) ? authorization.replaceFirst("Bearer ", "") : null;
       return token;
    }

    /**
     * (Controller) (Http Request)
     * Claims tokenInfo = tokenService.getTokenInfo(request);
     */
    public Claims getTokenInfo(HttpServletRequest request) {
        String token = getToken(request);
        if (token != null && !token.isEmpty() && !"undefined".equals(token)) {
            Claims tokenInfo = jwtUtil.extractAllClaims(token);
            return tokenInfo;
        }
        return null;
    }
}
