/*
 * Copyright 2025 Circle Internet Group, Inc. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.cybavo.reactnative.wallet.service;

import android.util.Log;

import com.cybavo.wallet.service.WalletSdk;
import com.cybavo.wallet.service.api.Error;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class CybavoWalletSdkModule extends ReactContextBaseJavaModule {

    private final static String TAG = CybavoWalletSdkModule.class.getSimpleName();
    private final ReactApplicationContext reactContext;

    public CybavoWalletSdkModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        WalletSdk.init(reactContext, null);
    }

    @Override
    public String getName() {
        return "WalletSdk";
    }

    @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();

        final Map<String, String> info = WalletSdk.getSDKInfo();
        final WritableMap sdkInfo = new WritableNativeMap();
        for (Map.Entry<String, String> entry : info.entrySet()) {
            sdkInfo.putString(entry.getKey(), entry.getValue());
        }
        constants.put("sdkInfo", sdkInfo);

        final WritableMap errorCodes = new WritableNativeMap();
        for (Field field : Error.Code.class.getFields()) {
            try {
                final String name = field.getName();
                final int value = field.getInt(null);
                errorCodes.putString(name, Integer.toString(value));
            } catch (Throwable error) {
                Log.e(TAG, "field failed", error);
            }
        }
        constants.put("ErrorCodes", errorCodes);

        return constants;
    }

    @ReactMethod
    public void init(ReadableMap configuration) {
        final String endpoint = configuration.getString("endpoint");
        final String apiCode = configuration.getString("apiCode");
        WalletSdk.init(this.reactContext,
                new WalletSdk.Configuration(endpoint, apiCode));
    }
}
