package btc

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"math"
	"net/http"
	"net/url"

	"git.sp4ke.com/sp4ke/bit4sat/config"
)

const (
	BitcoinAverageAPI = "https://apiv2.bitcoinaverage.com"
	BTCMsatRatio      = float64(100000000000)
)

var FixedRates = map[string]float64{
	"BTC": 1,
}

func FiatToMsat(currency string, amount float64) (int64, error) {
	rate, err := getRate(currency)
	if err != nil {
		return -1, err
	}

	return int64(math.Round((amount / rate) * BTCMsatRatio)), nil
}

func getRate(currency string) (float64, error) {
	pairName := "BTC" + currency

	reqParams := url.Values{}
	reqParams.Set("crypto", "BTC")
	reqParams.Set("fiat", currency)

	reqUri := fmt.Sprintf("%s/indices/global/ticker/short?%s",
		BitcoinAverageAPI, reqParams.Encode())

	// TODO: remove on prod and use normal client
	// Used for connectivity problems
	client := &http.Client{}
	if config.Env == "dev" {

		proxyUrl, err := url.Parse(config.HttpProxy)
		if err != nil {
			log.Fatal(err)
		}

		client.Transport = &http.Transport{
			Proxy: http.ProxyURL(proxyUrl),
		}

	}

	resp, err := client.Get(reqUri)
	if err != nil {
		return -1, err
	}

	var data map[string]interface{}

	dec := json.NewDecoder(resp.Body)
	err = dec.Decode(&data)
	if err != nil {
		log.Fatal(err)
	}

	pair := data[pairName]

	price, ok := pair.(map[string]interface{})["last"].(float64)
	if !ok {
		return -1, errors.New("bitcoinaverage parsing result")
	}

	return price, nil
}
