// Auto-generated by create-backlist
package <%= group %>.<%= projectName %>.security;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

@Service
public class JwtService {

  private final Key key;
  private final long expiresInMs;

  public JwtService(
      @Value("${JWT_SECRET:change_this_dev_secret_change_this_dev_secret}") String secret,
      @Value("${JWT_EXPIRES_IN_MS:18000000}") long expiresInMs // default 5h
  ) {
    // HS256 requires a sufficiently long secret (>= 32 bytes recommended)
    byte[] bytes = secret.getBytes(StandardCharsets.UTF_8);
    if (bytes.length < 32) {
      // pad (dev fallback). Better: set a proper secret in env.
      byte[] padded = new byte[32];
      System.arraycopy(bytes, 0, padded, 0, bytes.length);
      for (int i = bytes.length; i < 32; i++) padded[i] = (byte) 'x';
      bytes = padded;
    }
    this.key = Keys.hmacShaKeyFor(bytes);
    this.expiresInMs = expiresInMs;
  }

  /**
   * subject should be a stable identifier (email or userId)
   */
  public String generateToken(String subject) {
    long now = System.currentTimeMillis();
    return Jwts.builder()
        .setSubject(subject)
        .setIssuedAt(new Date(now))
        .setExpiration(new Date(now + expiresInMs))
        .signWith(key, SignatureAlgorithm.HS256)
        .compact();
  }

  public String validateAndGetSubject(String token) {
    try {
      return Jwts.parserBuilder()
          .setSigningKey(key)
          .build()
          .parseClaimsJws(token)
          .getBody()
          .getSubject();
    } catch (JwtException ex) {
      // signature invalid / expired / malformed
      throw new IllegalArgumentException("Invalid JWT token");
    }
  }
}