package official_product

import (
	"ai_scheduler/internal/config"
	"ai_scheduler/internal/pkg/l_request"
	"context"
	"encoding/json"
	"fmt"
	"strings"
)

type Client struct {
	cfg config.ToolConfig
}

func New(cfg config.ToolConfig) *Client {
	return &Client{
		cfg: cfg,
	}
}

// Call 调用销售同比分析接口
func (c *Client) Call(ctx context.Context, req OfficialProductRequest) (*OfficialProductData, error) {
	// 构建 URL 参数
	var queryParams []string

	if req.Page > 0 {
		queryParams = append(queryParams, fmt.Sprintf("page=%d", req.Page))
	}
	if req.Limit > 0 {
		queryParams = append(queryParams, fmt.Sprintf("limit=%d", req.Limit))
	}

	for _, pid := range req.OfficialProductIds {
		queryParams = append(queryParams, fmt.Sprintf("official_product_id[]=%s", pid))
	}

	for _, t := range req.Ct {
		queryParams = append(queryParams, fmt.Sprintf("ct[]=%s", strings.ReplaceAll(t, " ", "+")))
	}

	queryString := strings.Join(queryParams, "&")
	fullURL := fmt.Sprintf("%s?%s", c.cfg.BaseURL, queryString)

	headers := map[string]string{
		"Authorization": fmt.Sprintf("Bearer %s", c.cfg.APIKey),
	}

	reqObj := l_request.Request{
		Method:  "GET",
		Url:     fullURL,
		Headers: headers,
	}

	res, err := reqObj.Send()
	if err != nil {
		return nil, fmt.Errorf("请求失败，err: %v", err)
	}

	var resData OfficialProductResponse
	if err := json.Unmarshal([]byte(res.Text), &resData); err != nil {
		return nil, fmt.Errorf("解析响应失败，err: %v, resp: %s", err, res.Text)
	}

	if resData.Code != 200 {
		return nil, fmt.Errorf("业务错误，code: %d, msg: %s", resData.Code, resData.Msg)
	}

	return &resData.Data, nil
}
