package server

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"

	"route256/cart/internal/domain/entity"
	"route256/cart/internal/domain/model"

	"github.com/rs/zerolog/log"
)

func (s *Server) DeleteItemHandler(w http.ResponseWriter, r *http.Request) {
	strUserID := r.PathValue("user_id")
	userID, err := strconv.ParseInt(strUserID, 10, 64)
	if err != nil || userID <= 0 {
		if err == nil {
			err = fmt.Errorf("user_id must be greater than 0")
		}

		makeErrorResponse(w, err, http.StatusBadRequest)

		log.Trace().Err(err).Msgf("user_id=`%s`", strUserID)

		return
	}

	strSku := r.PathValue("sku_id")
	sku, err := strconv.ParseInt(strSku, 10, 64)
	if err != nil || sku <= 0 {
		if err == nil {
			err = fmt.Errorf("sku_id must be greater than 0")
		}

		makeErrorResponse(w, err, http.StatusBadRequest)

		log.Trace().Err(err).Msgf("sku_id=`%s`", strUserID)

		return
	}

	err = s.cartService.DeleteItem(r.Context(), entity.UID(userID), entity.Sku(sku))
	switch {
	case errors.Is(err, model.ErrCartNotFound), errors.Is(err, model.ErrItemNotFoundInCart), err == nil:
		w.WriteHeader(http.StatusNoContent)
	default:
		makeErrorResponse(w, err, http.StatusBadRequest)

		log.Trace().Err(err).Msgf("cartService.DeleteItemFromCart failed for uid=%d sku=%d: %d", userID, sku, http.StatusBadRequest)

		return
	}
}
