package util

import (
	"apskel-pos-be/internal/constants"
	"apskel-pos-be/internal/contract"
	"apskel-pos-be/internal/logger"
	"encoding/json"
	"net/http"
	"net/url"
)

func HandleResponse(w http.ResponseWriter, r *http.Request, response *contract.Response, methodName string) {
	var statusCode int
	if response.GetSuccess() {
		statusCode = http.StatusOK
	} else {
		responseError := response.GetErrors()[0]
		statusCode = MapErrorCodeToHttpStatus(responseError.GetCode())
	}
	WriteResponse(w, r, *response, statusCode, methodName)
}

func WriteResponse(w http.ResponseWriter, r *http.Request, resp contract.Response, statusCode int, methodName string) {
	w.WriteHeader(statusCode)
	response, err := json.Marshal(resp)
	if err != nil {
		logger.FromContext(r.Context()).Error(methodName, "unable to marshal json response", err)
	}
	_, err = w.Write(response)
	if err != nil {
		logger.FromContext(r.Context()).Error(methodName, "unable to write to response", err)
	}
}

func MapErrorCodeToHttpStatus(code string) int {
	statusCode := constants.HttpErrorMap[code]
	if statusCode == 0 {
		return http.StatusInternalServerError
	}
	return statusCode
}

func ExtractEndpointFromURL(requestURL string) string {
	parsedURL, err := url.Parse(requestURL)
	if err != nil {
		return "/"
	}
	return parsedURL.Path
}
