package handler

import (
	"errors"
	"net/http"

	"github.com/saveinmed/backend-go/internal/domain"
)

// CreateOrder godoc
// @Summary Criação de pedido com split
// @Tags Pedidos
// @Accept json
// @Produce json
// @Param order body createOrderRequest true "Pedido"
// @Success 201 {object} domain.Order
// @Router /api/v1/orders [post]
func (h *Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
	var req createOrderRequest
	if err := decodeJSON(r.Context(), r, &req); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	order := &domain.Order{
		BuyerID:  req.BuyerID,
		SellerID: req.SellerID,
		Items:    req.Items,
		Shipping: req.Shipping,
	}

	var total int64
	for _, item := range req.Items {
		total += item.UnitCents * item.Quantity
	}
	order.TotalCents = total

	if err := h.svc.CreateOrder(r.Context(), order); err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusCreated, order)
}

// ListOrders godoc
// @Summary Listar pedidos
// @Tags Pedidos
// @Security BearerAuth
// @Produce json
// @Success 200 {array} domain.Order
// @Router /api/v1/orders [get]
func (h *Handler) ListOrders(w http.ResponseWriter, r *http.Request) {
	page, pageSize := parsePagination(r)
	filter := domain.OrderFilter{}

	result, err := h.svc.ListOrders(r.Context(), filter, page, pageSize)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusOK, result)
}

// GetOrder godoc
// @Summary Consulta pedido
// @Tags Pedidos
// @Security BearerAuth
// @Produce json
// @Param id path string true "Order ID"
// @Success 200 {object} domain.Order
// @Router /api/v1/orders/{id} [get]
func (h *Handler) GetOrder(w http.ResponseWriter, r *http.Request) {
	id, err := parseUUIDFromPath(r.URL.Path)
	if err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	order, err := h.svc.GetOrder(r.Context(), id)
	if err != nil {
		writeError(w, http.StatusNotFound, err)
		return
	}

	writeJSON(w, http.StatusOK, order)
}

// UpdateOrderStatus godoc
// @Summary Atualiza status do pedido
// @Tags Pedidos
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param id path string true "Order ID"
// @Param status body updateStatusRequest true "Novo status"
// @Success 204 ""
// @Router /api/v1/orders/{id}/status [patch]
func (h *Handler) UpdateOrderStatus(w http.ResponseWriter, r *http.Request) {
	id, err := parseUUIDFromPath(r.URL.Path)
	if err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	var req updateStatusRequest
	if err := decodeJSON(r.Context(), r, &req); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	if !isValidStatus(req.Status) {
		writeError(w, http.StatusBadRequest, errors.New("invalid status"))
		return
	}

	if err := h.svc.UpdateOrderStatus(r.Context(), id, domain.OrderStatus(req.Status)); err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// DeleteOrder godoc
// @Summary Remover pedido
// @Tags Pedidos
// @Security BearerAuth
// @Param id path string true "Order ID"
// @Success 204 ""
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /api/v1/orders/{id} [delete]
func (h *Handler) DeleteOrder(w http.ResponseWriter, r *http.Request) {
	id, err := parseUUIDFromPath(r.URL.Path)
	if err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	if err := h.svc.DeleteOrder(r.Context(), id); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
