package wb

import (
	"fmt"
	"net/http"
	"sipro-mps/internal/marketplace"
	wbclient "sipro-mps/pkg/api/wb/client"
	"sipro-mps/pkg/utils"
	"time"
)

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

	authData, claims, err := utils.DecodeWildberriesJwt(mp.AuthDataJson)
	if err != nil {
		return nil, fmt.Errorf("failed to decode Wildberries JWT")
	}
	exp := claims["exp"].(float64)
	// chec if token is expired, for now unix date
	now := float64(time.Now().Unix())
	if exp < now {
		return nil, fmt.Errorf("token is expired")
	}
	securityHandler := NewWildberriesSecurityHandler(authData.Token)
	httpClient := &http.Client{
		Transport: NewRateLimitTransport(),
	}
	client, err := wbclient.NewClient("https://content-api.wildberries.ru", securityHandler, wbclient.WithClient(httpClient))
	if err != nil {
		return nil, fmt.Errorf("failed to create Wildberries client: %w", err)
	}
	return client, nil
}
