package handler

import (
	"strconv"

	"awesome-back/internal/domain/entities"
	"awesome-back/internal/service"
	"awesome-back/pkg/errors"

	"github.com/gin-gonic/gin"
)

type OrderHandler struct {
	orderService *service.OrderService
}

func NewOrderHandler(orderService *service.OrderService) *OrderHandler {
	return &OrderHandler{orderService: orderService}
}

func (h *OrderHandler) GetOrders(c *gin.Context) {
	orders, err := h.orderService.GetAllOrders()
	if err != nil {
		Error(c, err)
		return
	}

	Success(c, orders)
}

func (h *OrderHandler) GetOrderByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		Error(c, errors.NewInvalidError("invalid order ID format"))
		return
	}

	order, err := h.orderService.GetOrderByID(id)
	if err != nil {
		Error(c, err)
		return
	}

	Success(c, order)
}

func (h *OrderHandler) CreateOrder(c *gin.Context) {
	var order entities.Order
	if err := c.ShouldBindJSON(&order); err != nil {
		Error(c, errors.NewInvalidError("invalid order data"))
		return
	}

	err := h.orderService.CreateOrder(&order)
	if err != nil {
		Error(c, err)
		return
	}

	Created(c, order)
}
