package com.smyhub.infogenie.infogeniebackendjava.util;

import com.smyhub.infogenie.infogeniebackendjava.config.AppProperties;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * Validates the X-Site-Admin-Token request header against the configured secret.
 * Uses constant-time comparison to prevent timing attacks, mirroring Go's
 * crypto/subtle.ConstantTimeCompare.
 */
@Component
@RequiredArgsConstructor
public class AdminTokenUtil {

    public static final String ADMIN_TOKEN_HEADER = "X-Site-Admin-Token";

    private final AppProperties appProperties;

    /**
     * Returns true only when the header value matches the configured site admin token
     * and neither value is blank.
     */
    public boolean isValid(HttpServletRequest request) {
        String headerToken = request.getHeader(ADMIN_TOKEN_HEADER);
        String configToken = appProperties.getSiteAdminToken();

        if (headerToken == null || headerToken.isBlank() || configToken.isBlank()) {
            return false;
        }

        return constantTimeEquals(headerToken.getBytes(), configToken.getBytes());
    }

    private boolean constantTimeEquals(byte[] a, byte[] b) {
        try {
            byte[] digestA = MessageDigest.getInstance("SHA-256").digest(a);
            byte[] digestB = MessageDigest.getInstance("SHA-256").digest(b);
            return Arrays.equals(digestA, digestB) && Arrays.equals(a, b);
        } catch (Exception e) {
            return false;
        }
    }
}
