/*
 * Onbrix CRM Java SDK
 * Version: 1.0.0
 * License: MIT
 *
 * Copyright (c) 2026 Onbrix
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Usage:
 *
 *   OnbrixClient client = new OnbrixClient("crm_your_api_key", "https://your-instance.onbrix.com");
 *   List<OnbrixClient.Module> modules = client.modules().list();
 *   for (OnbrixClient.Module m : modules) {
 *       System.out.println(m.getName());
 *   }
 *
 * Requires Java 11+ (uses java.net.http.HttpClient).
 * No external dependencies.
 */

// Package: onbrix (package declaration omitted for single-file use)

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Onbrix CRM API client for Java.
 *
 * <p>Provides full access to the Onbrix REST API including module listing,
 * record CRUD operations, and webhook signature verification.</p>
 *
 * <p>All HTTP requests include automatic retry with exponential backoff
 * when rate-limited (HTTP 429).</p>
 *
 * <pre>{@code
 * OnbrixClient client = new OnbrixClient("crm_your_api_key", "https://your-instance.onbrix.com");
 *
 * // List modules
 * List<OnbrixClient.Module> modules = client.modules().list();
 *
 * // Create a record
 * Map<String, Object> data = new HashMap<>();
 * data.put("first_name", "John");
 * data.put("last_name", "Doe");
 * OnbrixClient.Record contact = client.records().create("contacts", data);
 * }</pre>
 */
public class OnbrixClient {

    /** The current version of the Onbrix Java SDK. */
    public static final String SDK_VERSION = "1.0.0";

    private static final String USER_AGENT = "onbrix-java/" + SDK_VERSION;
    private static final int MAX_RETRIES = 3;
    private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30);

    private final String apiKey;
    private final String baseUrl;
    private final HttpClient httpClient;
    private final ModuleResource moduleResource;
    private final RecordResource recordResource;

    /**
     * Creates a new Onbrix API client.
     *
     * @param apiKey  the API key for authentication (must start with "crm_")
     * @param baseUrl the base URL of the Onbrix instance (e.g., "https://your-instance.onbrix.com")
     * @throws IllegalArgumentException if apiKey or baseUrl is null or empty
     */
    public OnbrixClient(String apiKey, String baseUrl) {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("API key is required");
        }
        if (baseUrl == null || baseUrl.isBlank()) {
            throw new IllegalArgumentException("Base URL is required");
        }

        this.apiKey = apiKey;
        this.baseUrl = baseUrl.replaceAll("/+$", "");
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(DEFAULT_TIMEOUT)
                .build();
        this.moduleResource = new ModuleResource(this);
        this.recordResource = new RecordResource(this);
    }

    /**
     * Returns the module resource for listing CRM modules.
     *
     * @return the module resource
     */
    public ModuleResource modules() {
        return moduleResource;
    }

    /**
     * Returns the record resource for CRUD operations on module records.
     *
     * @return the record resource
     */
    public RecordResource records() {
        return recordResource;
    }

    // -----------------------------------------------------------------------
    // Webhook verification
    // -----------------------------------------------------------------------

    /**
     * Verifies the HMAC-SHA256 signature of an incoming webhook payload.
     *
     * <p>The signature should be in the format {@code sha256={hex_digest}} as received
     * in the {@code X-Webhook-Signature} header.</p>
     *
     * <pre>{@code
     * String body = ...; // raw request body
     * String signature = request.getHeader("X-Webhook-Signature");
     * if (!OnbrixClient.verifyWebhookSignature(body, signature, "your_webhook_secret")) {
     *     response.sendError(401, "Invalid signature");
     *     return;
     * }
     * }</pre>
     *
     * @param payload   the raw JSON request body
     * @param signature the signature from the X-Webhook-Signature header
     * @param secret    the webhook endpoint's signing secret
     * @return true if the signature is valid, false otherwise
     */
    public static boolean verifyWebhookSignature(String payload, String signature, String secret) {
        if (payload == null || signature == null || secret == null) {
            return false;
        }
        if (!signature.startsWith("sha256=")) {
            return false;
        }

        String receivedHex = signature.substring("sha256=".length());

        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(keySpec);
            byte[] computedHash = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
            String computedHex = bytesToHex(computedHash);

            // Constant-time comparison to prevent timing attacks
            return constantTimeEquals(receivedHex, computedHex);
        } catch (Exception e) {
            return false;
        }
    }

    // -----------------------------------------------------------------------
    // Internal HTTP methods
    // -----------------------------------------------------------------------

    /**
     * Sends an HTTP request to the Onbrix API with automatic retry on rate limiting.
     */
    String sendRequest(String method, String path, String jsonBody) throws OnbrixException {
        String url = baseUrl + "/api/v1" + path;
        int attempt = 0;

        while (true) {
            try {
                HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                        .uri(URI.create(url))
                        .timeout(DEFAULT_TIMEOUT)
                        .header("X-API-Key", apiKey)
                        .header("User-Agent", USER_AGENT)
                        .header("Accept", "application/json");

                if (jsonBody != null && ("POST".equals(method) || "PUT".equals(method))) {
                    requestBuilder.header("Content-Type", "application/json");
                    requestBuilder.method(method, HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8));
                } else if ("DELETE".equals(method)) {
                    requestBuilder.DELETE();
                } else {
                    requestBuilder.GET();
                }

                HttpResponse<String> response = httpClient.send(
                        requestBuilder.build(),
                        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)
                );

                int statusCode = response.statusCode();

                // Handle rate limiting with automatic retry
                if (statusCode == 429 && attempt < MAX_RETRIES) {
                    attempt++;
                    long sleepMs = calculateBackoffMs(response, attempt);
                    Thread.sleep(sleepMs);
                    continue;
                }

                if (statusCode >= 400) {
                    throwApiException(statusCode, response.body());
                }

                return response.body();

            } catch (OnbrixException e) {
                throw e;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new OnbrixException("Request interrupted", 0, null);
            } catch (IOException e) {
                throw new OnbrixException("Request failed: " + e.getMessage(), 0, null);
            } catch (Exception e) {
                throw new OnbrixException("Unexpected error: " + e.getMessage(), 0, null);
            }
        }
    }

    /**
     * Calculates the backoff duration in milliseconds for rate-limited request retries.
     */
    private static long calculateBackoffMs(HttpResponse<String> response, int attempt) {
        var resetHeader = response.headers().firstValue("X-RateLimit-Reset");
        if (resetHeader.isPresent()) {
            try {
                long resetUnix = Long.parseLong(resetHeader.get());
                long waitMs = (resetUnix * 1000) - System.currentTimeMillis();
                if (waitMs > 0) {
                    return waitMs;
                }
            } catch (NumberFormatException ignored) {
            }
        }
        // Exponential backoff: 1s, 2s, 4s
        return (long) (Math.pow(2, attempt - 1) * 1000);
    }

    /**
     * Parses an error response body and throws the appropriate typed exception.
     */
    private static void throwApiException(int statusCode, String responseBody) throws OnbrixException {
        String message = "HTTP " + statusCode;
        String errorCode = null;

        try {
            String parsedError = extractJsonStringValue(responseBody, "error");
            if (parsedError != null) {
                message = parsedError;
            }
            errorCode = extractJsonStringValue(responseBody, "code");
        } catch (Exception ignored) {
        }

        switch (statusCode) {
            case 401:
                throw new AuthenticationException(message, errorCode);
            case 403:
                throw new ForbiddenException(message, errorCode);
            case 404:
                throw new NotFoundException(message, errorCode);
            case 429:
                throw new RateLimitException(message, errorCode);
            case 400:
            case 422:
                throw new ValidationException(message, statusCode, errorCode);
            default:
                throw new OnbrixException(message, statusCode, errorCode);
        }
    }

    // -----------------------------------------------------------------------
    // Minimal JSON helpers (no external dependencies)
    // -----------------------------------------------------------------------

    /**
     * Serializes a map to a JSON object string.
     * Supports String, Number, Boolean, null, Map, and List values.
     */
    static String toJson(Map<String, Object> map) {
        if (map == null) return "null";
        StringBuilder sb = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) sb.append(",");
            first = false;
            sb.append("\"").append(escapeJsonString(entry.getKey())).append("\":");
            sb.append(valueToJson(entry.getValue()));
        }
        sb.append("}");
        return sb.toString();
    }

    /**
     * Converts a Java value to its JSON representation.
     */
    private static String valueToJson(Object value) {
        if (value == null) return "null";
        if (value instanceof String) return "\"" + escapeJsonString((String) value) + "\"";
        if (value instanceof Number) return value.toString();
        if (value instanceof Boolean) return value.toString();
        if (value instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> mapValue = (Map<String, Object>) value;
            return toJson(mapValue);
        }
        if (value instanceof List) {
            List<?> list = (List<?>) value;
            StringBuilder sb = new StringBuilder("[");
            boolean first = true;
            for (Object item : list) {
                if (!first) sb.append(",");
                first = false;
                sb.append(valueToJson(item));
            }
            sb.append("]");
            return sb.toString();
        }
        return "\"" + escapeJsonString(value.toString()) + "\"";
    }

    /**
     * Escapes special characters in a JSON string value.
     */
    private static String escapeJsonString(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"':  sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        return sb.toString();
    }

    /**
     * Extracts a string value from a JSON object by key name.
     * This is a lightweight parser for simple flat JSON objects.
     */
    static String extractJsonStringValue(String json, String key) {
        if (json == null) return null;
        String searchKey = "\"" + key + "\"";
        int keyIndex = json.indexOf(searchKey);
        if (keyIndex < 0) return null;

        int colonIndex = json.indexOf(':', keyIndex + searchKey.length());
        if (colonIndex < 0) return null;

        // Skip whitespace after colon
        int valueStart = colonIndex + 1;
        while (valueStart < json.length() && Character.isWhitespace(json.charAt(valueStart))) {
            valueStart++;
        }

        if (valueStart >= json.length()) return null;

        char firstChar = json.charAt(valueStart);
        if (firstChar == 'n' && json.startsWith("null", valueStart)) {
            return null;
        }

        if (firstChar != '"') return null;

        // Parse the string value, handling escape sequences
        StringBuilder sb = new StringBuilder();
        int i = valueStart + 1;
        while (i < json.length()) {
            char c = json.charAt(i);
            if (c == '\\' && i + 1 < json.length()) {
                char next = json.charAt(i + 1);
                switch (next) {
                    case '"':  sb.append('"');  i += 2; continue;
                    case '\\': sb.append('\\'); i += 2; continue;
                    case '/':  sb.append('/');  i += 2; continue;
                    case 'b':  sb.append('\b'); i += 2; continue;
                    case 'f':  sb.append('\f'); i += 2; continue;
                    case 'n':  sb.append('\n'); i += 2; continue;
                    case 'r':  sb.append('\r'); i += 2; continue;
                    case 't':  sb.append('\t'); i += 2; continue;
                    case 'u':
                        if (i + 5 < json.length()) {
                            String hex = json.substring(i + 2, i + 6);
                            sb.append((char) Integer.parseInt(hex, 16));
                            i += 6;
                            continue;
                        }
                        break;
                }
            }
            if (c == '"') break;
            sb.append(c);
            i++;
        }
        return sb.toString();
    }

    /**
     * Parses a JSON array of objects from a JSON string starting at the given position.
     * Returns a list of raw JSON object strings.
     */
    static List<String> parseJsonArray(String json, int startIndex) {
        List<String> items = new ArrayList<>();
        int i = startIndex;

        // Find array start
        while (i < json.length() && json.charAt(i) != '[') i++;
        if (i >= json.length()) return items;
        i++; // skip '['

        while (i < json.length()) {
            // Skip whitespace
            while (i < json.length() && Character.isWhitespace(json.charAt(i))) i++;
            if (i >= json.length() || json.charAt(i) == ']') break;

            if (json.charAt(i) == '{') {
                int objectStart = i;
                int depth = 0;
                boolean inString = false;
                while (i < json.length()) {
                    char c = json.charAt(i);
                    if (inString) {
                        if (c == '\\') { i++; } // skip escaped char
                        else if (c == '"') { inString = false; }
                    } else {
                        if (c == '"') { inString = true; }
                        else if (c == '{') { depth++; }
                        else if (c == '}') {
                            depth--;
                            if (depth == 0) { i++; break; }
                        }
                    }
                    i++;
                }
                items.add(json.substring(objectStart, i));
            } else {
                i++;
            }

            // Skip comma
            while (i < json.length() && (json.charAt(i) == ',' || Character.isWhitespace(json.charAt(i)))) i++;
        }

        return items;
    }

    /**
     * Extracts a JSON object value (as raw string) by key name.
     */
    static String extractJsonObjectValue(String json, String key) {
        if (json == null) return null;
        String searchKey = "\"" + key + "\"";
        int keyIndex = json.indexOf(searchKey);
        if (keyIndex < 0) return null;

        int colonIndex = json.indexOf(':', keyIndex + searchKey.length());
        if (colonIndex < 0) return null;

        int valueStart = colonIndex + 1;
        while (valueStart < json.length() && Character.isWhitespace(json.charAt(valueStart))) {
            valueStart++;
        }

        if (valueStart >= json.length()) return null;

        char firstChar = json.charAt(valueStart);

        // Object value
        if (firstChar == '{') {
            int depth = 0;
            boolean inString = false;
            int i = valueStart;
            while (i < json.length()) {
                char c = json.charAt(i);
                if (inString) {
                    if (c == '\\') { i++; }
                    else if (c == '"') { inString = false; }
                } else {
                    if (c == '"') { inString = true; }
                    else if (c == '{') { depth++; }
                    else if (c == '}') {
                        depth--;
                        if (depth == 0) return json.substring(valueStart, i + 1);
                    }
                }
                i++;
            }
        }

        // Array value
        if (firstChar == '[') {
            int depth = 0;
            boolean inString = false;
            int i = valueStart;
            while (i < json.length()) {
                char c = json.charAt(i);
                if (inString) {
                    if (c == '\\') { i++; }
                    else if (c == '"') { inString = false; }
                } else {
                    if (c == '"') { inString = true; }
                    else if (c == '[') { depth++; }
                    else if (c == ']') {
                        depth--;
                        if (depth == 0) return json.substring(valueStart, i + 1);
                    }
                }
                i++;
            }
        }

        // Primitive value (string, number, boolean, null)
        if (firstChar == '"') {
            return extractJsonStringValue(json, key);
        }

        // Number, boolean, null
        int endIndex = valueStart;
        while (endIndex < json.length()) {
            char c = json.charAt(endIndex);
            if (c == ',' || c == '}' || c == ']' || Character.isWhitespace(c)) break;
            endIndex++;
        }
        return json.substring(valueStart, endIndex);
    }

    /**
     * Extracts an integer value from a JSON object by key name.
     */
    static int extractJsonIntValue(String json, String key, int defaultValue) {
        String value = extractJsonObjectValue(json, key);
        if (value == null) return defaultValue;
        try {
            return Integer.parseInt(value.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * Parses a JSON object string into a Map.
     */
    static Map<String, Object> parseJsonObject(String json) {
        Map<String, Object> map = new HashMap<>();
        if (json == null || json.isBlank()) return map;

        json = json.trim();
        if (!json.startsWith("{") || !json.endsWith("}")) return map;

        // Remove outer braces
        String inner = json.substring(1, json.length() - 1).trim();
        if (inner.isEmpty()) return map;

        // Parse key-value pairs
        int i = 0;
        while (i < inner.length()) {
            // Skip whitespace
            while (i < inner.length() && Character.isWhitespace(inner.charAt(i))) i++;
            if (i >= inner.length()) break;

            // Parse key
            if (inner.charAt(i) != '"') break;
            int keyStart = i + 1;
            i = keyStart;
            while (i < inner.length() && inner.charAt(i) != '"') {
                if (inner.charAt(i) == '\\') i++;
                i++;
            }
            String mapKey = inner.substring(keyStart, i);
            i++; // skip closing quote

            // Skip colon
            while (i < inner.length() && (inner.charAt(i) == ':' || Character.isWhitespace(inner.charAt(i)))) i++;

            // Parse value
            if (i >= inner.length()) break;
            char vc = inner.charAt(i);
            if (vc == '"') {
                // String value
                String strVal = extractJsonStringValue("{\"k\":" + inner.substring(i) + "}", "k");
                map.put(mapKey, strVal);
                // Skip past the string
                i++;
                while (i < inner.length()) {
                    char sc = inner.charAt(i);
                    if (sc == '\\') { i += 2; continue; }
                    if (sc == '"') { i++; break; }
                    i++;
                }
            } else if (vc == '{') {
                String objStr = extractObjectAt(inner, i);
                map.put(mapKey, parseJsonObject(objStr));
                i += objStr.length();
            } else if (vc == '[') {
                String arrStr = extractArrayAt(inner, i);
                map.put(mapKey, arrStr); // Store as raw string
                i += arrStr.length();
            } else if (inner.startsWith("null", i)) {
                map.put(mapKey, null);
                i += 4;
            } else if (inner.startsWith("true", i)) {
                map.put(mapKey, Boolean.TRUE);
                i += 4;
            } else if (inner.startsWith("false", i)) {
                map.put(mapKey, Boolean.FALSE);
                i += 5;
            } else {
                // Number
                int numStart = i;
                while (i < inner.length()) {
                    char nc = inner.charAt(i);
                    if (nc == ',' || nc == '}' || nc == ']' || Character.isWhitespace(nc)) break;
                    i++;
                }
                String numStr = inner.substring(numStart, i).trim();
                if (numStr.contains(".")) {
                    map.put(mapKey, Double.parseDouble(numStr));
                } else {
                    try {
                        map.put(mapKey, Long.parseLong(numStr));
                    } catch (NumberFormatException e) {
                        map.put(mapKey, numStr);
                    }
                }
            }

            // Skip comma and whitespace
            while (i < inner.length() && (inner.charAt(i) == ',' || Character.isWhitespace(inner.charAt(i)))) i++;
        }

        return map;
    }

    private static String extractObjectAt(String s, int start) {
        int depth = 0;
        boolean inStr = false;
        int i = start;
        while (i < s.length()) {
            char c = s.charAt(i);
            if (inStr) {
                if (c == '\\') { i++; }
                else if (c == '"') { inStr = false; }
            } else {
                if (c == '"') { inStr = true; }
                else if (c == '{') { depth++; }
                else if (c == '}') {
                    depth--;
                    if (depth == 0) return s.substring(start, i + 1);
                }
            }
            i++;
        }
        return s.substring(start);
    }

    private static String extractArrayAt(String s, int start) {
        int depth = 0;
        boolean inStr = false;
        int i = start;
        while (i < s.length()) {
            char c = s.charAt(i);
            if (inStr) {
                if (c == '\\') { i++; }
                else if (c == '"') { inStr = false; }
            } else {
                if (c == '"') { inStr = true; }
                else if (c == '[') { depth++; }
                else if (c == ']') {
                    depth--;
                    if (depth == 0) return s.substring(start, i + 1);
                }
            }
            i++;
        }
        return s.substring(start);
    }

    /**
     * Converts a byte array to a lowercase hex string.
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    /**
     * Performs constant-time string comparison to prevent timing attacks.
     */
    private static boolean constantTimeEquals(String a, String b) {
        if (a.length() != b.length()) return false;
        int result = 0;
        for (int i = 0; i < a.length(); i++) {
            result |= a.charAt(i) ^ b.charAt(i);
        }
        return result == 0;
    }

    // -----------------------------------------------------------------------
    // Exception classes
    // -----------------------------------------------------------------------

    /**
     * Base exception for all Onbrix API errors.
     * Contains the HTTP status code and a machine-readable error code.
     */
    public static class OnbrixException extends Exception {
        private final int statusCode;
        private final String errorCode;

        /**
         * Creates a new OnbrixException.
         *
         * @param message    a human-readable error description
         * @param statusCode the HTTP status code
         * @param errorCode  the machine-readable error code, or null
         */
        public OnbrixException(String message, int statusCode, String errorCode) {
            super(message);
            this.statusCode = statusCode;
            this.errorCode = errorCode;
        }

        /** Returns the HTTP status code. */
        public int getStatusCode() { return statusCode; }

        /** Returns the machine-readable error code, or null. */
        public String getErrorCode() { return errorCode; }

        @Override
        public String toString() {
            String s = "OnbrixException: " + getMessage() + " (status=" + statusCode;
            if (errorCode != null) s += ", code=" + errorCode;
            return s + ")";
        }
    }

    /**
     * Thrown when the API key is missing, invalid, or expired (HTTP 401).
     */
    public static class AuthenticationException extends OnbrixException {
        /** Creates a new AuthenticationException. */
        public AuthenticationException(String message, String errorCode) {
            super(message, 401, errorCode);
        }
    }

    /**
     * Thrown when the authenticated user lacks permission for the requested operation (HTTP 403).
     */
    public static class ForbiddenException extends OnbrixException {
        /** Creates a new ForbiddenException. */
        public ForbiddenException(String message, String errorCode) {
            super(message, 403, errorCode);
        }
    }

    /**
     * Thrown when the requested resource does not exist (HTTP 404).
     */
    public static class NotFoundException extends OnbrixException {
        /** Creates a new NotFoundException. */
        public NotFoundException(String message, String errorCode) {
            super(message, 404, errorCode);
        }
    }

    /**
     * Thrown when the request data fails validation (HTTP 400 or 422).
     */
    public static class ValidationException extends OnbrixException {
        /** Creates a new ValidationException. */
        public ValidationException(String message, int statusCode, String errorCode) {
            super(message, statusCode, errorCode);
        }
    }

    /**
     * Thrown when the API rate limit has been exceeded and all retry attempts are exhausted (HTTP 429).
     */
    public static class RateLimitException extends OnbrixException {
        /** Creates a new RateLimitException. */
        public RateLimitException(String message, String errorCode) {
            super(message, 429, errorCode);
        }
    }

    // -----------------------------------------------------------------------
    // Data model classes
    // -----------------------------------------------------------------------

    /**
     * Represents a CRM module (e.g., Contacts, Leads, Deals).
     */
    public static class Module {
        private final String id;
        private final String name;
        private final String slug;
        private final String description;
        private final String createdAt;
        private final String updatedAt;

        /**
         * Creates a Module from parsed JSON values.
         */
        Module(String id, String name, String slug, String description, String createdAt, String updatedAt) {
            this.id = id;
            this.name = name;
            this.slug = slug;
            this.description = description;
            this.createdAt = createdAt;
            this.updatedAt = updatedAt;
        }

        /** Returns the unique identifier of the module. */
        public String getId() { return id; }

        /** Returns the display name of the module. */
        public String getName() { return name; }

        /** Returns the URL-friendly slug used in API paths. */
        public String getSlug() { return slug; }

        /** Returns the description of the module, or null. */
        public String getDescription() { return description; }

        /** Returns the creation timestamp, or null. */
        public String getCreatedAt() { return createdAt; }

        /** Returns the last update timestamp, or null. */
        public String getUpdatedAt() { return updatedAt; }

        @Override
        public String toString() {
            return "Module{id='" + id + "', name='" + name + "', slug='" + slug + "'}";
        }

        /**
         * Parses a Module from a raw JSON object string.
         */
        static Module fromJson(String json) {
            return new Module(
                    extractJsonStringValue(json, "id"),
                    extractJsonStringValue(json, "name"),
                    extractJsonStringValue(json, "slug"),
                    extractJsonStringValue(json, "description"),
                    extractJsonStringValue(json, "created_at"),
                    extractJsonStringValue(json, "updated_at")
            );
        }
    }

    /**
     * Represents a single record within a module.
     */
    public static class Record {
        private final String id;
        private final Map<String, Object> data;
        private final String createdBy;
        private final String updatedBy;
        private final String createdAt;
        private final String updatedAt;

        /**
         * Creates a Record from parsed values.
         */
        Record(String id, Map<String, Object> data, String createdBy, String updatedBy, String createdAt, String updatedAt) {
            this.id = id;
            this.data = data != null ? Collections.unmodifiableMap(data) : Collections.emptyMap();
            this.createdBy = createdBy;
            this.updatedBy = updatedBy;
            this.createdAt = createdAt;
            this.updatedAt = updatedAt;
        }

        /** Returns the unique identifier of the record. */
        public String getId() { return id; }

        /** Returns the field values as an unmodifiable map. */
        public Map<String, Object> getData() { return data; }

        /** Returns the user ID of the record creator, or null. */
        public String getCreatedBy() { return createdBy; }

        /** Returns the user ID of the last updater, or null. */
        public String getUpdatedBy() { return updatedBy; }

        /** Returns the creation timestamp, or null. */
        public String getCreatedAt() { return createdAt; }

        /** Returns the last update timestamp, or null. */
        public String getUpdatedAt() { return updatedAt; }

        @Override
        public String toString() {
            return "Record{id='" + id + "', data=" + data + "}";
        }

        /**
         * Parses a Record from a raw JSON object string.
         */
        static Record fromJson(String json) {
            String dataJson = extractJsonObjectValue(json, "data");
            Map<String, Object> dataMap = (dataJson != null && dataJson.startsWith("{"))
                    ? parseJsonObject(dataJson) : new HashMap<>();
            return new Record(
                    extractJsonStringValue(json, "id"),
                    dataMap,
                    extractJsonStringValue(json, "created_by"),
                    extractJsonStringValue(json, "updated_by"),
                    extractJsonStringValue(json, "created_at"),
                    extractJsonStringValue(json, "updated_at")
            );
        }
    }

    /**
     * Pagination metadata for list responses.
     */
    public static class Meta {
        private final int total;
        private final int page;
        private final int pageSize;
        private final int totalPages;

        /**
         * Creates a Meta from parsed values.
         */
        Meta(int total, int page, int pageSize, int totalPages) {
            this.total = total;
            this.page = page;
            this.pageSize = pageSize;
            this.totalPages = totalPages;
        }

        /** Returns the total number of records matching the query. */
        public int getTotal() { return total; }

        /** Returns the current page number (1-based). */
        public int getPage() { return page; }

        /** Returns the number of records per page. */
        public int getPageSize() { return pageSize; }

        /** Returns the total number of pages. */
        public int getTotalPages() { return totalPages; }

        @Override
        public String toString() {
            return "Meta{total=" + total + ", page=" + page + ", pageSize=" + pageSize + ", totalPages=" + totalPages + "}";
        }

        /**
         * Parses a Meta from a raw JSON object string.
         */
        static Meta fromJson(String json) {
            return new Meta(
                    extractJsonIntValue(json, "total", 0),
                    extractJsonIntValue(json, "page", 1),
                    extractJsonIntValue(json, "page_size", 20),
                    extractJsonIntValue(json, "total_pages", 0)
            );
        }
    }

    /**
     * A paginated list of records with metadata.
     */
    public static class ListResponse {
        private final List<Record> data;
        private final Meta meta;

        /**
         * Creates a ListResponse.
         */
        ListResponse(List<Record> data, Meta meta) {
            this.data = data != null ? Collections.unmodifiableList(data) : Collections.emptyList();
            this.meta = meta;
        }

        /** Returns the list of records on the current page. */
        public List<Record> getData() { return data; }

        /** Returns the pagination metadata. */
        public Meta getMeta() { return meta; }

        @Override
        public String toString() {
            return "ListResponse{records=" + data.size() + ", meta=" + meta + "}";
        }

        /**
         * Parses a ListResponse from a raw JSON string.
         */
        static ListResponse fromJson(String json) {
            // Parse meta
            String metaJson = extractJsonObjectValue(json, "meta");
            Meta meta = metaJson != null ? Meta.fromJson(metaJson) : new Meta(0, 1, 20, 0);

            // Parse data array
            List<Record> records = new ArrayList<>();
            String dataKey = "\"data\"";
            int dataIndex = json.indexOf(dataKey);
            if (dataIndex >= 0) {
                int colonIndex = json.indexOf(':', dataIndex + dataKey.length());
                if (colonIndex >= 0) {
                    List<String> rawRecords = parseJsonArray(json, colonIndex + 1);
                    for (String rawRecord : rawRecords) {
                        records.add(Record.fromJson(rawRecord));
                    }
                }
            }

            return new ListResponse(records, meta);
        }
    }

    /**
     * The result of a delete operation.
     */
    public static class DeleteResponse {
        private final String id;
        private final boolean deleted;

        /**
         * Creates a DeleteResponse.
         */
        DeleteResponse(String id, boolean deleted) {
            this.id = id;
            this.deleted = deleted;
        }

        /** Returns the identifier of the deleted record. */
        public String getId() { return id; }

        /** Returns true if the record was successfully deleted. */
        public boolean isDeleted() { return deleted; }

        @Override
        public String toString() {
            return "DeleteResponse{id='" + id + "', deleted=" + deleted + "}";
        }

        /**
         * Parses a DeleteResponse from a raw JSON string.
         */
        static DeleteResponse fromJson(String json) {
            String dataJson = extractJsonObjectValue(json, "data");
            if (dataJson == null) dataJson = json;
            String id = extractJsonStringValue(dataJson, "id");
            String deletedStr = extractJsonObjectValue(dataJson, "deleted");
            boolean deleted = "true".equals(deletedStr != null ? deletedStr.trim() : "false");
            return new DeleteResponse(id, deleted);
        }
    }

    /**
     * Configures filtering, sorting, and pagination for list requests.
     */
    public static class ListOptions {
        private Integer page;
        private Integer pageSize;
        private String sortBy;
        private String sortDir;
        private String search;
        private Map<String, String> filters;

        /** Creates empty ListOptions. Use the setter methods to configure. */
        public ListOptions() {}

        /** Sets the page number (1-based). */
        public ListOptions page(int page) { this.page = page; return this; }

        /** Sets the number of records per page. */
        public ListOptions pageSize(int pageSize) { this.pageSize = pageSize; return this; }

        /** Sets the field name to sort by. */
        public ListOptions sortBy(String sortBy) { this.sortBy = sortBy; return this; }

        /** Sets the sort direction: "asc" or "desc". */
        public ListOptions sortDir(String sortDir) { this.sortDir = sortDir; return this; }

        /** Sets the full-text search query. */
        public ListOptions search(String search) { this.search = search; return this; }

        /**
         * Sets the filter map. Each entry produces a filter[field]=value query parameter.
         */
        public ListOptions filters(Map<String, String> filters) { this.filters = filters; return this; }

        /**
         * Adds a single filter. Creates the filter map if it does not exist.
         *
         * @param field the field name to filter by
         * @param value the value to match
         * @return this ListOptions for chaining
         */
        public ListOptions filter(String field, String value) {
            if (this.filters == null) this.filters = new HashMap<>();
            this.filters.put(field, value);
            return this;
        }

        /** Returns the configured page number, or null if not set. */
        public Integer getPage() { return page; }

        /** Returns the configured page size, or null if not set. */
        public Integer getPageSize() { return pageSize; }

        /** Returns the configured sort field, or null. */
        public String getSortBy() { return sortBy; }

        /** Returns the configured sort direction, or null. */
        public String getSortDir() { return sortDir; }

        /** Returns the configured search query, or null. */
        public String getSearch() { return search; }

        /** Returns the configured filters, or null. */
        public Map<String, String> getFilters() { return filters; }

        /**
         * Builds the query string from these options.
         */
        String toQueryString() {
            List<String> parts = new ArrayList<>();
            if (page != null) parts.add("page=" + page);
            if (pageSize != null) parts.add("page_size=" + pageSize);
            if (sortBy != null && !sortBy.isBlank())
                parts.add("sort_by=" + URLEncoder.encode(sortBy, StandardCharsets.UTF_8));
            if (sortDir != null && !sortDir.isBlank())
                parts.add("sort_dir=" + URLEncoder.encode(sortDir, StandardCharsets.UTF_8));
            if (search != null && !search.isBlank())
                parts.add("search=" + URLEncoder.encode(search, StandardCharsets.UTF_8));
            if (filters != null) {
                for (Map.Entry<String, String> entry : filters.entrySet()) {
                    parts.add("filter[" + URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "]="
                            + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
                }
            }
            return parts.isEmpty() ? "" : "?" + String.join("&", parts);
        }
    }

    // -----------------------------------------------------------------------
    // Resource classes
    // -----------------------------------------------------------------------

    /**
     * Provides methods for listing CRM modules.
     * Access via {@link OnbrixClient#modules()}.
     */
    public static class ModuleResource {
        private final OnbrixClient client;

        ModuleResource(OnbrixClient client) {
            this.client = client;
        }

        /**
         * Lists all modules available to the authenticated user.
         *
         * @return a list of available modules
         * @throws OnbrixException if the API returns an error
         */
        public List<Module> list() throws OnbrixException {
            String json = client.sendRequest("GET", "/modules", null);
            List<Module> modules = new ArrayList<>();

            String dataKey = "\"data\"";
            int dataIndex = json.indexOf(dataKey);
            if (dataIndex >= 0) {
                int colonIndex = json.indexOf(':', dataIndex + dataKey.length());
                if (colonIndex >= 0) {
                    List<String> rawModules = parseJsonArray(json, colonIndex + 1);
                    for (String raw : rawModules) {
                        modules.add(Module.fromJson(raw));
                    }
                }
            }

            return modules;
        }
    }

    /**
     * Provides methods for CRUD operations on module records.
     * Access via {@link OnbrixClient#records()}.
     */
    public static class RecordResource {
        private final OnbrixClient client;

        RecordResource(OnbrixClient client) {
            this.client = client;
        }

        /**
         * Lists records from the specified module with optional filtering, sorting, and pagination.
         *
         * @param moduleSlug the module slug (e.g., "contacts", "leads")
         * @param options    optional list options, may be null for defaults
         * @return a paginated list of records with metadata
         * @throws OnbrixException if the API returns an error
         */
        public ListResponse list(String moduleSlug, ListOptions options) throws OnbrixException {
            Objects.requireNonNull(moduleSlug, "moduleSlug is required");
            String queryString = options != null ? options.toQueryString() : "";
            String path = "/" + URLEncoder.encode(moduleSlug, StandardCharsets.UTF_8) + queryString;
            String json = client.sendRequest("GET", path, null);
            return ListResponse.fromJson(json);
        }

        /**
         * Lists records using default options.
         *
         * @param moduleSlug the module slug
         * @return a paginated list of records
         * @throws OnbrixException if the API returns an error
         */
        public ListResponse list(String moduleSlug) throws OnbrixException {
            return list(moduleSlug, null);
        }

        /**
         * Retrieves a single record by its ID.
         *
         * @param moduleSlug the module slug
         * @param recordId   the unique identifier of the record
         * @return the requested record
         * @throws NotFoundException if the record does not exist
         * @throws OnbrixException   if the API returns an error
         */
        public Record get(String moduleSlug, String recordId) throws OnbrixException {
            Objects.requireNonNull(moduleSlug, "moduleSlug is required");
            Objects.requireNonNull(recordId, "recordId is required");
            String path = "/" + URLEncoder.encode(moduleSlug, StandardCharsets.UTF_8)
                    + "/" + URLEncoder.encode(recordId, StandardCharsets.UTF_8);
            String json = client.sendRequest("GET", path, null);
            String dataJson = extractJsonObjectValue(json, "data");
            if (dataJson == null) {
                throw new OnbrixException("Failed to parse record response", 0, null);
            }
            return Record.fromJson(dataJson);
        }

        /**
         * Creates a new record in the specified module.
         *
         * @param moduleSlug the module slug
         * @param data       a map of field names to values
         * @return the newly created record
         * @throws ValidationException if the data fails validation
         * @throws OnbrixException     if the API returns an error
         */
        public Record create(String moduleSlug, Map<String, Object> data) throws OnbrixException {
            Objects.requireNonNull(moduleSlug, "moduleSlug is required");
            Objects.requireNonNull(data, "data is required");
            String path = "/" + URLEncoder.encode(moduleSlug, StandardCharsets.UTF_8);
            Map<String, Object> body = new HashMap<>();
            body.put("data", data);
            String json = client.sendRequest("POST", path, toJson(body));
            String dataJson = extractJsonObjectValue(json, "data");
            if (dataJson == null) {
                throw new OnbrixException("Failed to parse create response", 0, null);
            }
            return Record.fromJson(dataJson);
        }

        /**
         * Updates an existing record. Only the provided fields will be changed.
         *
         * @param moduleSlug the module slug
         * @param recordId   the unique identifier of the record
         * @param data       a map of field names to their new values
         * @return the updated record
         * @throws NotFoundException   if the record does not exist
         * @throws ValidationException if the data fails validation
         * @throws OnbrixException     if the API returns an error
         */
        public Record update(String moduleSlug, String recordId, Map<String, Object> data) throws OnbrixException {
            Objects.requireNonNull(moduleSlug, "moduleSlug is required");
            Objects.requireNonNull(recordId, "recordId is required");
            Objects.requireNonNull(data, "data is required");
            String path = "/" + URLEncoder.encode(moduleSlug, StandardCharsets.UTF_8)
                    + "/" + URLEncoder.encode(recordId, StandardCharsets.UTF_8);
            Map<String, Object> body = new HashMap<>();
            body.put("data", data);
            String json = client.sendRequest("PUT", path, toJson(body));
            String dataJson = extractJsonObjectValue(json, "data");
            if (dataJson == null) {
                throw new OnbrixException("Failed to parse update response", 0, null);
            }
            return Record.fromJson(dataJson);
        }

        /**
         * Deletes a record by its ID.
         *
         * @param moduleSlug the module slug
         * @param recordId   the unique identifier of the record
         * @return a response indicating whether the record was deleted
         * @throws NotFoundException if the record does not exist
         * @throws OnbrixException   if the API returns an error
         */
        public DeleteResponse delete(String moduleSlug, String recordId) throws OnbrixException {
            Objects.requireNonNull(moduleSlug, "moduleSlug is required");
            Objects.requireNonNull(recordId, "recordId is required");
            String path = "/" + URLEncoder.encode(moduleSlug, StandardCharsets.UTF_8)
                    + "/" + URLEncoder.encode(recordId, StandardCharsets.UTF_8);
            String json = client.sendRequest("DELETE", path, null);
            return DeleteResponse.fromJson(json);
        }
    }
}
