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 CheckoutResponse struct {
	OrderID int64 `json:"order_id"`
}

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

	orderID, err := s.cartService.CheckoutUserCart(r.Context(), entity.UID(userID))
	switch {
	case errors.Is(err, model.ErrCartNotFound):
		makeErrorResponse(w, err, http.StatusNotFound)

		return
	case err != nil:
		makeErrorResponse(w, err, http.StatusInternalServerError)

		return
	}

	resp := CheckoutResponse{
		OrderID: orderID,
	}

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

		return
	}
}
