package com.rehome.jpahefengweather.utils;

import net.i2p.crypto.eddsa.EdDSAEngine;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Base64;

public class JwtUtils {
    public static String getJwt(){
        try {
            // Private key
            String privateKeyString = "MC4CAQAwBQYDK2VwBCIEIOtI2Yuhkyor4Zfny9OUMbzMmZCEJ7hqIpuoDhk0zYcy";
            privateKeyString = privateKeyString.trim().replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").trim();
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
            PKCS8EncodedKeySpec encoded = new PKCS8EncodedKeySpec(privateKeyBytes);
            PrivateKey privateKey = new EdDSAPrivateKey(encoded);

            // Header
            String headerJson = "{\"alg\": \"EdDSA\", \"kid\": \"C4B98RHV2D\"}";

            // Payload
            long iat = ZonedDateTime.now(ZoneOffset.UTC).toEpochSecond() - 30;
            long exp = iat + 900;
            String payloadJson = "{\"sub\": \"278AVHGU9W\", \"iat\": " + iat + ", \"exp\": " + exp + "}";

            // Base64url header+payload
            String headerEncoded = Base64.getUrlEncoder().encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
            String payloadEncoded = Base64.getUrlEncoder().encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
            String data = headerEncoded + "." + payloadEncoded;

            EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519);

            // Sign
            final Signature s = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm()));
            s.initSign(privateKey);
            s.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signature = s.sign();

            String signatureString = Base64.getUrlEncoder().encodeToString(signature);

            System.out.println("Signature: \n" + signatureString);

            // Print Token
            String jwt = data + "." + signatureString;
            System.out.println("JWT: \n" + jwt);
            return jwt;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
