package kr.co.accura.wbx.spring.auth;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import kr.co.accura.wbx.spring.config.WbxSpringProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

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

@Component
@RequiredArgsConstructor
public class JwtProvider {

    private final WbxSpringProperties props;

    /**
     * WBX FastAPI 호환 JWT 생성
     * 필수 claims: sub(email), user_id — WBX가 이 두 필드로 사용자 식별
     */
    public String generateToken(WbxUserDetails user) {
        return Jwts.builder()
                .claims(Map.of(
                        "sub", user.getEmail(),
                        "user_id", user.getId(),
                        "username", user.getUsername(),
                        "full_name", user.getFullName(),
                        "email", user.getEmail(),
                        "is_admin", user.isAdmin(),
                        "department_id", user.getDepartmentId() != null ? user.getDepartmentId() : 0,
                        "roles", user.getRoles() != null ? user.getRoles() : List.of()
                ))
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + props.getJwt().getExpiration() * 1000))
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * MFA 임시 토큰 (5분, API 접근 불가)
     */
    public String generateMfaToken(WbxUserDetails user) {
        return Jwts.builder()
                .claims(Map.of(
                        "user_id", user.getId(),
                        "mfa_pending", true
                ))
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + 300_000)) // 5 minutes
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * JWT 검증 후 claims 추출
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    /**
     * MFA 토큰인지 확인
     */
    public boolean isMfaToken(Claims claims) {
        return Boolean.TRUE.equals(claims.get("mfa_pending", Boolean.class));
    }

    private SecretKey getSigningKey() {
        byte[] keyBytes = props.getJwt().getSecret().getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
