package cart

import (
	"git.gocasts.ir/ebhomengo/niki/domain/shoppingbasket/service"
	"git.gocasts.ir/ebhomengo/niki/pkg/claim"
	httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
	"git.gocasts.ir/ebhomengo/niki/types"
	"github.com/labstack/echo/v4"
	"net/http"
	"strconv"
)

type Handler struct {
	svc service.Service
}

func NewHandler(svc service.Service) Handler {
	return Handler{svc: svc}
}

func (h Handler) AddToBasket(c echo.Context) error {
	claims := claim.GetClaimsFromEchoContext(c)

	var req service.AddToCartRequest
	if err := c.Bind(&req); err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{
			"error": "invalid request body",
		})
	}

	req.UserID = types.ID(claims.UserID)
	if err := h.svc.AddToBasket(c.Request().Context(), req); err != nil {
		msg, code := httpmsg.Error(err)
		return c.JSON(code, msg)
	}

	return c.NoContent(http.StatusNoContent)
}

func (h Handler) GetCart(c echo.Context) error {
	claims := claim.GetClaimsFromEchoContext(c)

	res, err := h.svc.GetCart(c.Request().Context(), types.ID(claims.UserID))
	if err != nil {
		msg, code := httpmsg.Error(err)
		return c.JSON(code, msg)
	}

	return c.JSON(http.StatusOK, res)
}

func (h Handler) RemoveCart(c echo.Context) error {
	claims := claim.GetClaimsFromEchoContext(c)

	if err := h.svc.ClearCart(c.Request().Context(), types.ID(claims.UserID)); err != nil {
		msg, code := httpmsg.Error(err)
		return c.JSON(code, msg)
	}

	return c.NoContent(http.StatusNoContent)
}

func (h Handler) RemoveItem(c echo.Context) error {
	claims := claim.GetClaimsFromEchoContext(c)
	p := c.Param("productID")

	pID, err := strconv.Atoi(p)
	if err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{
			"error": "invalid product id",
		})
	}

	var req service.RemoveFromCartRequest

	req.UserID = types.ID(claims.UserID)
	req.ProductID = types.ID(pID)

	if err := h.svc.RemoveFromCart(c.Request().Context(), req); err != nil {
		msg, code := httpmsg.Error(err)
		return c.JSON(code, msg)
	}

	return c.NoContent(http.StatusNoContent)
}

func (h Handler) UpdateQuantity(c echo.Context) error {
	claims := claim.GetClaimsFromEchoContext(c)
	p := c.Param("productID")

	pID, err := strconv.Atoi(p)
	if err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{
			"error": "invalid product id",
		})
	}

	qStr := c.Param("quantity")
	q, err := strconv.Atoi(qStr)
	if err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{
			"error": "invalid quantity",
		})
	}

	var req service.UpdateQuantityRequest
	req.UserID = types.ID(claims.UserID)
	req.ProductID = types.ID(pID)
	req.Quantity = q

	if err := h.svc.UpdateQuantity(c.Request().Context(), req); err != nil {
		msg, code := httpmsg.Error(err)
		return c.JSON(code, msg)
	}

	return c.NoContent(http.StatusNoContent)
}
