import fetch from 'node-fetch';

import { NetworkProxy } from './typings'
import CfExceptionHandler from "../../core/CfExceptionHandler";

export default class CfNetwork implements NetworkProxy{
    private config

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

    public async get(url:string):Promise<Object> {

        try {
            const config = {
                ...this.config,
                method: 'GET'
            }

            const response = (await fetch(`${url}`, config))
            const fetchedData = await response.json()
            console.log('Data Fetched: ', fetchedData)
            return fetchedData

        } 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> {
        try {
            const config = {
                ...this.config,
                body: JSON.stringify(payload),
                method: 'POST'
            }
            const postData = (await fetch(url, config))
            return postData

        } catch(e) {
            console.error('Error sending data: ', e)
            if(!url.includes("sdk/crash")){
                new CfExceptionHandler().throwAndLogError('API Error', e.toString())
            }        }
    }

}
