package loms

import (
	"context"
	"fmt"

	"route256/cart/internal/domain/entity"
	"route256/cart/internal/domain/model"

	pbLoms "route256/pkg/api/loms/v1"
)

type Service struct {
	grpcClient pbLoms.LOMSClient
}

func NewLomsService(grpcClient pbLoms.LOMSClient) *Service {
	return &Service{
		grpcClient: grpcClient,
	}
}

func (s *Service) OrderCreate(ctx context.Context, cart *model.Cart) (int64, error) {
	items := make([]*pbLoms.OrderItem, len(cart.Items))
	for i, item := range cart.Items {
		items[i] = &pbLoms.OrderItem{
			Sku:   int64(item.Product.Sku),
			Count: item.Count,
		}
	}

	req := &pbLoms.OrderCreateRequest{
		UserId: int64(cart.UserID),
		Items:  items,
	}

	resp, err := s.grpcClient.OrderCreate(ctx, req)
	if err != nil {
		return 0, fmt.Errorf("grpcClient.OrderCreate: %w", err)
	}

	return resp.OrderId, nil
}

func (s *Service) StocksInfo(ctx context.Context, sku entity.Sku) (uint32, error) {
	req := &pbLoms.StocksInfoRequest{
		Sku: int64(sku),
	}

	resp, err := s.grpcClient.StocksInfo(ctx, req)
	if err != nil {
		return 0, fmt.Errorf("grpcClient.StocksInfo: %w", err)
	}

	return resp.Count, nil
}
