package com.kamco.cd.kamcoback.auth;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import javax.crypto.SecretKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtTokenProvider {

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

  @Value("${jwt.access-token-validity-in-ms}")
  private long accessTokenValidityInMs;

  @Value("${jwt.refresh-token-validity-in-ms}")
  private long refreshTokenValidityInMs;

  private SecretKey key;

  @PostConstruct
  public void init() {
    // HS256용 SecretKey
    this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
  }

  public String createAccessToken(String subject) {
    return createToken(subject, accessTokenValidityInMs);
  }

  public String createRefreshToken(String subject) {
    return createToken(subject, refreshTokenValidityInMs);
  }

  private String createToken(String subject, long validityInMs) {
    Date now = new Date();
    Date expiry = new Date(now.getTime() + validityInMs);
    return Jwts.builder().subject(subject).issuedAt(now).expiration(expiry).signWith(key).compact();
  }

  public String getSubject(String token) {
    var claims = parseClaims(token).getPayload();
    return claims.getSubject();
  }

  public boolean isValidToken(String token) {
    try {
      Jws<Claims> claims = parseClaims(token);
      return !claims.getPayload().getExpiration().before(new Date());
    } catch (Exception e) {
      return false;
    }
  }

  private Jws<Claims> parseClaims(String token) {
    return Jwts.parser()
        .verifyWith(key) // SecretKey 타입
        .build()
        .parseSignedClaims(token);
  }

  public long getRefreshTokenValidityInMs() {
    return refreshTokenValidityInMs;
  }
}
