package server

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

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

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

type AddItemRequest struct {
	Count uint32 `json:"count" validate:"required,gt=0"`
}

func (s *Server) AddItemHandler(w http.ResponseWriter, r *http.Request) {
	var request AddItemRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		makeErrorResponse(w, err, http.StatusBadRequest)

		log.Trace().Err(err).Msg("failed decoding request")

		return
	}
	defer r.Body.Close()

	if request.Count <= 0 {
		err := fmt.Errorf("count must be greater than 0")

		makeErrorResponse(w, err, http.StatusBadRequest)

		log.Trace().Err(err).Msg("body validation failed")

		return
	}

	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
	}

	item := &model.Item{
		Product: &model.Product{
			Name:  "",
			Price: 0,
			Sku:   entity.Sku(sku),
		},
		Count: request.Count,
	}

	uid := entity.UID(userID)

	if err := s.cartService.AddItem(r.Context(), uid, item); err != nil {
		switch {
		case errors.Is(err, model.ErrProductNotFound), errors.Is(err, model.ErrNotEnoughStocks):
			makeErrorResponse(w, err, http.StatusPreconditionFailed)

			log.Trace().Err(err).Msgf("product does not exist")
		default:
			makeErrorResponse(w, err, http.StatusInternalServerError)

			log.Trace().Err(err).Msgf("unknown error")
		}

		return
	}

	w.WriteHeader(http.StatusOK)
}
