package com.mosquito.project.support;

import com.mosquito.project.persistence.entity.ApiKeyEntity;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public final class TestAuthSupport {

    public static final String RAW_API_KEY = "test-api-key-000000000000";
    public static final String API_KEY_PREFIX = RAW_API_KEY.substring(0, Math.min(12, RAW_API_KEY.length())).trim();

    private TestAuthSupport() {
    }

    public static ApiKeyEntity buildApiKeyEntity() {
        try {
            byte[] salt = "test-salt-1234567890".getBytes(StandardCharsets.UTF_8);
            String saltBase64 = Base64.getEncoder().encodeToString(salt);
            javax.crypto.SecretKeyFactory skf = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            javax.crypto.spec.PBEKeySpec spec = new javax.crypto.spec.PBEKeySpec(
                RAW_API_KEY.toCharArray(),
                salt,
                185000,
                256
            );
            byte[] derived = skf.generateSecret(spec).getEncoded();
            String hashBase64 = Base64.getEncoder().encodeToString(derived);

            ApiKeyEntity entity = new ApiKeyEntity();
            entity.setKeyPrefix(API_KEY_PREFIX);
            entity.setSalt(saltBase64);
            entity.setKeyHash(hashBase64);
            return entity;
        } catch (Exception ex) {
            throw new IllegalStateException("Failed to build test API key", ex);
        }
    }
}
