package com.fiuu.xdk.reactnative;

import org.json.JSONObject;

/**
 * Normalizes Fiuu transaction payloads and decides which RN callback should receive them.
 * Package-visible for unit tests.
 */
final class TransactionResultHandler {

    enum Route {
        SUCCESS,
        PENDING,
        FAILURE,
        MALFORMED
    }

    static final class Dispatch {
        final Route route;
        final String payload;
        final String message;

        private Dispatch(Route route, String payload, String message) {
            this.route = route;
            this.payload = payload;
            this.message = message;
        }

        static Dispatch success(String payload) {
            return new Dispatch(Route.SUCCESS, payload, null);
        }

        static Dispatch pending(String payload) {
            return new Dispatch(Route.PENDING, payload, null);
        }

        static Dispatch failure(String payload) {
            return new Dispatch(Route.FAILURE, payload, null);
        }

        static Dispatch malformed(String message) {
            return new Dispatch(Route.MALFORMED, null, message);
        }
    }

    private TransactionResultHandler() {
    }

    static String extractStatusCode(JSONObject result) {
        String statCode = result.optString("StatCode", "").trim();
        if (!statCode.isEmpty()) {
            return statCode;
        }
        return result.optString("status_code", "").trim();
    }

    static Dispatch classify(String transactionResult) {
        if (transactionResult == null || transactionResult.isEmpty()) {
            return Dispatch.malformed("Payment completed but no transaction result was returned.");
        }

        try {
            JSONObject result = new JSONObject(transactionResult);
            String statusCode = extractStatusCode(result);

            if ("00".equals(statusCode)) {
                return Dispatch.success(transactionResult);
            }
            if ("22".equals(statusCode)) {
                return Dispatch.pending(transactionResult);
            }
            // Close/cancel and other XDK results often have no StatCode. Keep the
            // original JSON so merchants see the native payload instead of a
            // wrapper-invented "payment completed" message.
            return Dispatch.failure(transactionResult);
        } catch (Exception e) {
            return Dispatch.malformed("Payment completed but transaction result was malformed.");
        }
    }
}
