package de.oaa.xxx.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

@Service
public class JwtService {

    private static final long EXPIRATION_MS = 24L * 60 * 60 * 1000; // 24 Stunden

    private final PrivateKey privateKey;
    private final PublicKey publicKey;

    public JwtService(
            @Value("${jwt.keystore.path}") Resource keystoreResource,
            @Value("${jwt.keystore.password}") String password,
            @Value("${jwt.keystore.alias}") String alias) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(keystoreResource.getInputStream(), password.toCharArray());
        this.privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        this.publicKey = keyStore.getCertificate(alias).getPublicKey();
    }

    public String generateToken(String email, String name) {
        return Jwts.builder()
                .subject(email)
                .claim("name", name)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_MS))
                .signWith(privateKey)
                .compact();
    }

    public Claims validateAndGetClaims(String token) {
        return Jwts.parser()
                .verifyWith(publicKey)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
}
