// internal/service/order_service.go
package service

import (
	"awesome-back/internal/domain/entities"
	"awesome-back/internal/domain/repositories"
	"awesome-back/pkg/errors"
)

type OrderService struct {
	orderRepo repositories.OrderRepository
}

func NewOrderService(orderRepo repositories.OrderRepository) *OrderService {
	return &OrderService{orderRepo: orderRepo}
}

func (s *OrderService) GetAllOrders() ([]entities.Order, error) {
	orders, err := s.orderRepo.FindAll()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get orders")
	}
	return orders, nil
}

func (s *OrderService) GetOrderByID(id int) (*entities.Order, error) {
	if id <= 0 {
		return nil, errors.NewInvalidError("invalid order ID")
	}

	order, err := s.orderRepo.FindByID(id)
	if err != nil {
		if errors.IsNotFound(err) {
			return nil, errors.NewNotFoundError("order not found")
		}
		return nil, errors.Wrap(err, "failed to get order")
	}

	return order, nil
}

func (s *OrderService) CreateOrder(order *entities.Order) error {
	if order == nil {
		return errors.NewInvalidError("order cannot be nil")
	}

	if len(order.Items) == 0 {
		return errors.NewInvalidError("order must contain at least one item")
	}

	err := s.orderRepo.Save(order)
	if err != nil {
		return errors.Wrap(err, "failed to create order")
	}

	return nil
}
