import axios from "axios";
import {NetworkProxy} from "./typings";
import CfExceptionHandler from "../../core/CfExceptionHandler";
import isBrowser from "is-in-browser";

export default class CfNetwork implements NetworkProxy {
    private config;

    constructor(key: string) {
        this.config = {
            headers: {
                Authorization: `Bearer ${key}`,
            },
        };
    }

    public async get(url: string): Promise<Object | undefined> {
        try {
            return (await axios.get(`${url}`, this.config)).data;
        } catch (e) {
            console.error("Error retrieving data: ", e);

            if (url.includes("nudge")) {
                new CfExceptionHandler().throwNudgeFetchError(
                    "nudge fetch API",
                    e.toString()
                );
            } else {
                new CfExceptionHandler().throwAndLogError("API Error", e.toString());
            }
        }
    }

    public async send(url: string, payload: any) : Promise<Object | undefined> {
        try {
            return await axios.post(url, payload, this.config);
        } catch (error) {
            if (!url.includes("sdk/crash")) {
                new CfExceptionHandler().throwAPIError(
                    "API Error",
                    `URL: ${url}\n\nerror.response: ${error.response.toString()}\n\nerror.response.data: ${
                        error.response.data
                    }`
                );
            }
            throw error;
        }
    }

    /**
     * Checks if the environment is online.
     * In browser: uses navigator.onLine only (no fetch, avoids CORS issues).
     * In Node.js: always returns true.
     * Optionally, pass a testUrl for advanced use (may cause CORS errors).
     */
    public isOnline(): boolean {
        if (!isBrowser) {
            // Node.js or non-browser environment
            return true;
        }
        // Browser environment
        if (
            typeof window !== "undefined" &&
            typeof window.navigator !== "undefined" &&
            !window.navigator.onLine
        ) {
            return false;
        }
        // Fallback
        return true;
    }
}
