package org.example.utils;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

public class KcvCheckTest {
    public static byte[] generateKCV(byte[] keyBytes) throws Exception {
        // 8-byte zero block
        byte[] zeroBlock = new byte[8];

        // Create the key for 3DES
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // Encrypt zero block
        byte[] encrypted = cipher.doFinal(zeroBlock);

        // Return first 3 bytes (6 hex characters)
        return Arrays.copyOfRange(encrypted, 0, 4);
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    // Utility to convert byte array to hex string
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes)
            sb.append(String.format("%02X", b));
        return sb.toString();
    }
    private static byte[] expandTo24Bytes(byte[] key16) {
        byte[] key24 = new byte[24];
        System.arraycopy(key16, 0, key24, 0, 16);
        System.arraycopy(key16, 0, key24, 16, 8); // Repeat first 8 bytes
        return key24;
    }


    @SneakyThrows
    @Test
    public  void testKcv()  {
        // Example 3DES key: 16-byte key (will be padded internally)
        String hexKey = "730BC451D6D64CAB0B37A486049E6DC4";
        byte[] keyBytes = expandTo24Bytes(hexStringToByteArray(hexKey));

        byte[] kcv = generateKCV(keyBytes);
        System.out.println("KCV: " + bytesToHex(kcv));
    }
}
