package com.hpay.hpay_mobile_api.security;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@SuppressWarnings("ALL")
@Component
public class JwtTokenUtil {

    // The secret key for signing the JWT token. It should be kept safe.
   // private final String secretKey = "MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAT4wggE8AgEAAkEAmP9xuI9lNNfe2Dzf0lXZnnXOsLh5nHoAqfRiB92cFNtE61oFqLa96pGV8j1sBzYFxlVz37F6DiQmdB1eJAvtDLc7Jl4qChIcxO0LfJqF1qS0WnE7MejtOpyCOz5pNzF2hKefG94X2p1gPfZpGSDoEXdgsApyM1Yvghu1ge14Qx4ovkq55vBO61Bjsn0weodk4C0sOjsj9g4xwv63XYjAHblE1LrfZbA2jd3rDRrkftM1Hzz6dxp9VbhtxG+meoJ5ZGi2y+hZ3+Y8WBYDlTIu08U8I9JZjRpHp9tZ2kbvRNeXybebhslwR0gbfiV2m6vYc8qxFnQ==";  // It's advisable to store this in a safe location (e.g., environment variable)

    // Method to generate the JWT token
    private String secretKey = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eWpxb3JzcGF1dXdnYW5mZyYxMjM0";  // Example: "bXlTZWNyZXRLZXk="

    public String generateToken(String username) {
        // Ensure the secret key is valid and decode it properly
        Key key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), SignatureAlgorithm.HS256.getJcaName());

        // Create the JWT token
        return Jwts.builder()
                .setSubject(username)               // Set the subject of the token
                .setIssuedAt(new Date())            // Set the issued date
                .setExpiration(new Date(System.currentTimeMillis() + 86400000))  // 1 day expiration (24 hours): 86400000
                .signWith(key, SignatureAlgorithm.HS256)  // Sign with the decoded key and HS256 algorithm
                .compact();  // Compact and return the JWT token
    }


    // Extract username (subject) from the token
    public String extractUsername(String token) {
        // Parse the token to get the Claims (JWT claims)
        Claims claims = parseClaims(token);
        return claims.getSubject();
    }


    // Validate the token by comparing the username and checking expiration
    public boolean validateToken(String token, String username) {
        String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }


    // Check if the token is expired
    private boolean isTokenExpired(String token) {
        Date expiration = parseClaims(token).getExpiration();
        return expiration.before(new Date());
    }

    // Parse the claims from the token
    private Claims parseClaims(String token) {
        // Create a Key using the secret key and HMAC SHA256 algorithm
        Key key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), SignatureAlgorithm.HS256.getJcaName());

        // Parse the token using the key and extract claims
        return Jwts.parser()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

}
