package com.cameleer.server.app.security;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Validates bootstrap tokens used for initial agent registration.
 * <p>
 * Uses constant-time comparison ({@link MessageDigest#isEqual}) to prevent
 * timing attacks. Supports dual-token rotation: both the current and previous
 * bootstrap tokens are accepted during a rotation window.
 */
public class BootstrapTokenValidator {

    private final SecurityProperties properties;

    public BootstrapTokenValidator(SecurityProperties properties) {
        this.properties = properties;
    }

    /**
     * Validates the provided token against the configured bootstrap token(s).
     *
     * @param provided the token to validate
     * @return true if the token matches the current or previous bootstrap token
     */
    public boolean validate(String provided) {
        if (provided == null || provided.isBlank()) {
            return false;
        }

        byte[] providedBytes = provided.getBytes(StandardCharsets.UTF_8);

        // Check current token, then previous token (rotation support)
        String currentToken = properties.getBootstrapToken();
        String previousToken = properties.getBootstrapTokenPrevious();
        return (currentToken != null
                    && MessageDigest.isEqual(providedBytes, currentToken.getBytes(StandardCharsets.UTF_8)))
                || (previousToken != null
                    && MessageDigest.isEqual(providedBytes, previousToken.getBytes(StandardCharsets.UTF_8)));
    }
}
