package ozon

import (
	"errors"
	"git.denco.store/fakz9/ozon-api-client/ozon"
	"github.com/tidwall/gjson"
	"net/http"
	"sipro-mps/internal/marketplace"
)

func GetClientFromMarketplace(mp *marketplace.Marketplace) (*ozon.Client, error) {

	authDataParsed := gjson.Parse(mp.AuthData)
	clientIdResult := authDataParsed.Get("clientId")
	apiKeyResult := authDataParsed.Get("clientToken")
	if !clientIdResult.Exists() || !apiKeyResult.Exists() {
		return nil, errors.New("auth data is not valid")
	}
	apiKey := apiKeyResult.String()
	clientId := clientIdResult.String()
	httpClient := &http.Client{
		Transport: NewRateLimitTransport(),
	}
	opts := []ozon.ClientOption{
		ozon.WithAPIKey(apiKey),
		ozon.WithClientId(clientId),
		ozon.WithHttpClient(httpClient),
	}
	client := ozon.NewClient(opts...)
	if client == nil {
		return nil, errors.New("failed to create ozon client")
	}

	return client, nil
}
