package ym

import (
	"errors"
	"git.denco.store/fakz9/yandex-go-client"
	"net/http"
	"sipro-mps/internal/marketplace"
	"strings"

	"github.com/tidwall/gjson"
)

func GetClientFromMarketplace(mp *marketplace.Marketplace) (*ymclient.APIClient, error) {
	authDataParsed := gjson.Parse(mp.AuthData)
	apiKeyResult := authDataParsed.Get("apiKey")
	if !apiKeyResult.Exists() {
		return nil, errors.New("API key not found in marketplace auth data")
	}
	apiKey := apiKeyResult.String()
	if apiKey == "" {
		return nil, errors.New("API key is empty")
	}
	if !strings.HasPrefix(apiKey, "ACMA") {
		return nil, errors.New("API key does not start with 'ACMA'")
	}
	// Create HTTP client with rate limiting
	httpClient := &http.Client{
		Transport: NewRateLimitTransport(),
	}

	cfg := ymclient.NewConfiguration()
	cfg.AddDefaultHeader("Api-Key", apiKey)
	cfg.HTTPClient = httpClient
	client := ymclient.NewAPIClient(cfg)
	return client, nil
}
