package server

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

	"route256/cart/internal/domain/entity"

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

type CartItem struct {
	Sku   int64  `json:"sku"`
	Name  string `json:"name"`
	Count uint32 `json:"count"`
	Price uint32 `json:"price"`
}

type GetUserCartResponse struct {
	Items      []CartItem `json:"items"`
	TotalPrice uint32     `json:"total_price"`
}

func (s *Server) GetItemsByUserIDHandler(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
	}

	cart, err := s.cartService.GetItemsByUserID(r.Context(), entity.UID(userID))
	if err != nil {
		makeErrorResponse(w, err, http.StatusNotFound)

		log.Trace().Err(err).Msgf("cartService.GetItemsByUserID: %d", http.StatusNotFound)

		return
	}

	response := GetUserCartResponse{
		Items:      make([]CartItem, len(cart.Items)),
		TotalPrice: cart.TotalPrice,
	}
	for i, v := range cart.Items {
		response.Items[i] = CartItem{
			Sku:   int64(v.Product.Sku),
			Name:  v.Product.Name,
			Count: v.Count,
			Price: uint32(v.Product.Price),
		}
	}

	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(response); err != nil {
		makeErrorResponse(w, err, http.StatusInternalServerError)

		return
	}
}
