package product_upload

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

type Client struct {
	cfg config.ToolConfig
}

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

func (c *Client) Call(ctx context.Context, toolReq *ProductUploadRequest) (toolResp *ProductUploadResponse, err error) {
	// 商品有且只能有一个
	if len(toolReq.GoodsList) != 1 {
		return nil, errors.New("商品只能有一个")
	}

	apiReq, _ := util.StructToMap(toolReq)

	req := l_request.Request{
		Method: "Post",
		Url:    c.cfg.BaseURL,
		Json:   apiReq,
	}
	res, err := req.Send()

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

	type resType struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
		Data struct {
			Ids []int `json:"ids"` // 商品 IDs
		} `json:"data"`
	}
	var resMap resType
	err = json.Unmarshal([]byte(res.Text), &resMap)
	if err != nil {
		return nil, fmt.Errorf("解析响应失败，err: %v", err)
	}
	if resMap.Code != 200 {
		return nil, fmt.Errorf("业务错误，code: %d, msg: %s", resMap.Code, resMap.Msg)
	}
	if len(resMap.Data.Ids) == 0 {
		return nil, fmt.Errorf("ids为空")
	}

	toolResp = &ProductUploadResponse{
		PreviewUrl: c.cfg.AddURL,
		SpuNum:     toolReq.GoodsList[0].GoodsInfo.SpuNum,
		Id:         resMap.Data.Ids[0],
	}

	return toolResp, nil
}
