package sale_order

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/AlchemyTelcoSolutions/callisto-so-bff/internal/domain/model"
	"go.uber.org/zap"
)

// CreateOrder is a function that create order in SO service
// Getting information from callisto-api
func (s *Service) CreateOrder(r *http.Request) *model.SaleOrderResponse {
	// prepare path in callisto api
	config := s.configs.GetConfigurations().CallistoAPI
	urlCreate := strings.Join([]string{config.Host, config.SaleOrder.Create}, "")

	// log the request to callisto api
	logRequestBody(r, urlCreate, "body to callisto api create Order from cart", s.logger)

	return s.commonCreateOrder(r, urlCreate)
}

// CreateOrderFromAuction is a function that create order in SO service coming from one auction
// Getting information from callisto-api
func (s *Service) CreateOrderFromAuction(r *http.Request, bidID string) *model.SaleOrderResponse {
	// preare path in callisto api
	config := s.configs.GetConfigurations().CallistoAPI
	pathCreateFromAuction := fmt.Sprintf(config.Bids.SetWinner, bidID)
	urlCreate := strings.Join([]string{config.Host, pathCreateFromAuction}, "")
	// log the request to callisto api
	logRequestBody(r, urlCreate, "body to callisto api create order from auction(bid set_winner)", s.logger)

	return s.commonCreateOrder(r, urlCreate)
}

func (s *Service) commonCreateOrder(r *http.Request, path string) *model.SaleOrderResponse {
	response := &model.SaleOrderResponse{}
	createOrderApi := &model.CallistoApiResponse{}

	// send request to callisto api
	responseCode, err := s.sendRequestToAPI(r, path, createOrderApi)
	if err != nil {
		msg := fmt.Sprintf("error proxy call to callisto-api for create order %s", err.Error())
		s.logger.Error(msg, err, zap.String("ctx2", CALLISTO_API), zap.String("path", path))
		if http.StatusOK < responseCode && responseCode < http.StatusInternalServerError {
			return defaultResponse(response, err.Error(), responseCode)
		}
		return defaultResponse(response, msg, http.StatusInternalServerError)
	}

	s.logger.Info("got response from callisto api", zap.Any("response", createOrderApi), zap.String("ctx2", CALLISTO_API))

	// send order to callisto so
	if err := s.sendOrderToSOService(r.Context(), createOrderApi); err != nil {
		// nothing to do, only log the error if any
		// at this moment was decided to continue the execution even if Callisto SO returns with error
		msg := fmt.Sprintf("error sending order to callisto sale order service %s", err.Error())
		s.logger.Info(msg, zap.String("ctx2", CALLISTO_SO_GRPC))
	}

	response.Code = responseCode
	response.Response = createOrderApi
	return response
}
