package org.openautonomousconnection.webserver.utils;

import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket;

import java.util.Collections;
import java.util.Locale;
import java.util.Map;

/**
 * Reads parameters from WebRequestPacket headers (case-insensitive).
 *
 * <p>Additionally provides hashing helpers via a supplied {@link WebHasher}.
 */
public final class RequestParams {

    private final Map<String, String> headers;

    /**
     * Creates a param reader.
     *
     * @param request request
     */
    public RequestParams(WebRequestPacket request) {
        Map<String, String> h = request != null ? request.getHeaders() : null;
        this.headers = (h == null) ? Collections.emptyMap() : h;
    }

    /**
     * Gets a header (case-insensitive).
     *
     * @param key key
     * @return value or null
     */
    public String get(String key) {
        if (key == null) return null;
        String needle = key.toLowerCase(Locale.ROOT);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            if (e.getKey() != null && e.getKey().toLowerCase(Locale.ROOT).equals(needle)) {
                return e.getValue();
            }
        }
        return null;
    }

    /**
     * Gets a header or default.
     *
     * @param key key
     * @param def default
     * @return value or default
     */
    public String getOr(String key, String def) {
        String v = get(key);
        return (v == null) ? def : v;
    }

    /**
     * Parses an int header.
     *
     * @param key key
     * @param def default
     * @return int
     */
    public int getInt(String key, int def) {
        String v = get(key);
        if (v == null) return def;
        try {
            return Integer.parseInt(v.trim());
        } catch (Exception ignored) {
            return def;
        }
    }

    /**
     * Returns a trimmed header value.
     *
     * @param key key
     * @return trimmed value or null
     */
    public String getTrimmed(String key) {
        String v = get(key);
        if (v == null) return null;
        String t = v.trim();
        return t.isEmpty() ? null : t;
    }

    /**
     * Returns SHA-256 hex of a header value.
     *
     * @param hasher hasher
     * @param key header key
     * @return sha256 hex (or null if missing)
     */
    public String getSha256Hex(WebHasher hasher, String key) {
        String v = getTrimmed(key);
        if (v == null) return null;
        return hasher.sha256Hex(v);
    }
}
