package api

import (
	"net/http"

	v1 "github.com/AlchemyTelcoSolutions/callisto-so-bff/api/v1"
	"github.com/AlchemyTelcoSolutions/callisto-so-bff/internal/api/converter"
)

// CreateFromCart is a function that create a SO from cart
func (s *Server) CreateFromCart(w http.ResponseWriter, r *http.Request) {
	response := s.saleOrderSvc.CreateOrder(r)
	s.respWithJson(w, response.Code, converter.ToHTTPPostSaleOrders(*response))
}

// CreateFromAuction is a function that create a SO from Auction
func (s *Server) CreateFromAuction(w http.ResponseWriter, r *http.Request, bidID string) {
	response := s.saleOrderSvc.CreateOrderFromAuction(r, bidID)
	s.respWithJson(w, response.Code, converter.ToHTTPPostSaleOrders(*response))
}

func (s *Server) UpdateSaleOrder(w http.ResponseWriter, r *http.Request, orderReference string) {
	req := &v1.UpdateSaleOrderMultipartBody{}
	response := s.saleOrderSvc.UpdateSaleOrder(r, req, orderReference)
	s.respWithJson(w, response.Code, converter.ToHTTPPostUpdateSaleOrders(*response))
}

// GetSOSummary is a function that get sale order summary group by status
func (s *Server) GetSOSummary(w http.ResponseWriter, r *http.Request) {
	soCfg := s.cfg.GetConfigurations().CallistoSO

	if soCfg.Enabled && soCfg.Config.GetSOSummary.IsEnabled {
		// feature flag enable
		// send request to callisto-so
		response := s.saleOrderSvc.GetSOSummary(r)
		s.respWithJson(w, response.Code, converter.ToHTTPResponse(response))
		return
	}

	// forward request to callisto-api
	s.ForwarRequest(w, r, r.URL.Path)
}

// ForwarRequest is the default function when path is not found proxy the call to Callisto-api
func (s *Server) ForwarRequest(w http.ResponseWriter, r *http.Request, fromPath string) {
	resp := s.proxyService.ForwardProxy(r, fromPath)
	s.respFromProxy(w, resp.StatusCode, resp.BodyBytes)
}

// ExportASNToFile is a function that generate file for ASN data
func (s *Server) ExportASNToFile(w http.ResponseWriter, r *http.Request, orderReference string, fileFormat v1.ExportASNToFileParams) {
	response := s.saleOrderSvc.ExportASNToFile(r, orderReference, string(fileFormat.Format))
	if !response.Success {
		s.respWithJson(w, response.Code, response.Error)
		return
	}

	s.respWithFile(w, response.File)
}
