package com.lesingle.edu.common.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * JWT Token Provider
 */
@Slf4j
@Component
public class JwtTokenProvider {

    @Value("${jwt.secret}")
    private String secret;

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

    private SecretKey secretKey;

    /**
     * 获取 token 过期时间（毫秒）
     */
    public long getExpiration() {
        return expiration;
    }

    @PostConstruct
    public void init() {
        this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    public String generateToken(JwtPayload payload) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .subject(payload.getUsername())
                .claim("userId", payload.getUserId())
                .claim("username", payload.getUsername())
                .claim("role", payload.getRole())
                .claim("tenantId", payload.getTenantId())
                .claim("name", payload.getName())
                .issuedAt(now)
                .expiration(expiryDate)
                .signWith(secretKey)
                .compact();
    }

    public JwtPayload getPayloadFromToken(String token) {
        Claims claims = Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token)
                .getPayload();

        return JwtPayload.builder()
                .userId(claims.get("userId", Long.class))
                .username(claims.get("username", String.class))
                .role(claims.get("role", String.class))
                .tenantId(claims.get("tenantId", Long.class))
                .name(claims.get("name", String.class))
                .build();
    }

    /**
     * 验证 token 是否有效
     * @param token token 字符串
     * @return true-有效，false-无效
     */
    public boolean validateToken(String token) {
        return validateTokenWithReason(token) == null;
    }

    /**
     * 验证 token 并返回错误原因
     * @param token token 字符串
     * @return 错误原因字符串，如果 token 有效则返回 null
     */
    public String validateTokenWithReason(String token) {
        try {
            Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(token);
            return null; // token 有效
        } catch (MalformedJwtException e) {
            log.error("Invalid JWT token: {}", e.getMessage());
            return "TOKEN_INVALID";
        } catch (ExpiredJwtException e) {
            log.error("Expired JWT token: {}", e.getMessage());
            return "TOKEN_EXPIRED";
        } catch (UnsupportedJwtException e) {
            log.error("Unsupported JWT token: {}", e.getMessage());
            return "TOKEN_UNSUPPORTED";
        } catch (IllegalArgumentException e) {
            log.error("JWT claims string is empty: {}", e.getMessage());
            return "TOKEN_EMPTY";
        } catch (Exception e) {
            log.error("JWT validation error: {}", e.getMessage());
            return "TOKEN_INVALID";
        }
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .getSubject();
    }

    /**
     * 获取 token 剩余过期时间（秒）
     * @param token token 字符串
     * @return 剩余秒数，如果 token 无效则返回 0
     */
    public long getRemainingExpiration(String token) {
        try {
            Date expiryDate = Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload()
                    .getExpiration();
            long remaining = (expiryDate.getTime() - System.currentTimeMillis()) / 1000;
            return remaining > 0 ? remaining : 0;
        } catch (Exception e) {
            log.warn("获取 token 剩余过期时间失败：{}", e.getMessage());
            return 0;
        }
    }

}
