package http

import (
	"bytes"
	"encoding/json"
	"golang.source-fellows.com/pattern/circuitbreaker/internal"
	"io"
	"log"
	"net/http"
)

var emptyResult = internal.TxResult{}

type PaymentServiceProvider struct {
}

func NewPaymentServiceProvider() *PaymentServiceProvider {
	return &PaymentServiceProvider{}
}

func (p *PaymentServiceProvider) RequestPayment(amount float64, data internal.CustomerData) (internal.TxResult, error) {

	log.Println("payment service provider method")

	jsonData, err := json.Marshal(data)
	if err != nil {
		return emptyResult, nil
	}

	response, err := http.Post("http://localhost:8080", "application/json", bytes.NewReader(jsonData))
	if err != nil {
		return emptyResult, err
	}
	defer response.Body.Close()

	resultBites, err := io.ReadAll(response.Body)
	if err != nil {
		return emptyResult, err
	}

	result := internal.TxResult{}
	err = json.Unmarshal(resultBites, &result)
	if err != nil {
		return emptyResult, err
	}

	return result, nil
}
