package cart

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	httpclient "github.com/UpmeshLTD/urus-aio/infrastructure/client/http"
	"github.com/UpmeshLTD/urus-aio/paid-order/config"
)

type Service interface {
	GetCartByIDs(ctx context.Context, token string, ids []string) ([]*CartDetail, error)
}

type serviceImpl struct {
	cfg config.Config
}

func NewService(cfg config.Config) Service {
	return &serviceImpl{
		cfg: cfg,
	}
}

func (s *serviceImpl) GetCartByIDs(ctx context.Context, token string, ids []string) ([]*CartDetail, error) {
	path := ""
	for index, value := range ids {
		if index > 0 {
			path = path + "&"
		}
		path = path + "ids=" + value
	}

	res, err := s.request(ctx, http.MethodGet, path, token, nil)
	if err != nil {
		return nil, err
	}
	var getCartByIDResponse []*CartDetail
	if err = json.Unmarshal(res, &getCartByIDResponse); err != nil {
		return nil, err
	}

	return getCartByIDResponse, nil
}

func (s *serviceImpl) request(ctx context.Context, method, queryParams, token string, body interface{}) (result []byte, err error) {
	url := fmt.Sprintf("%s?%s", s.cfg.GetCartServiceConfig().Endpoint, queryParams)
	headers := map[string]interface{}{
		"Authorization": token,
	}
	return httpclient.Do(ctx, method, url, body, headers)
}
