package goods_add

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

type Client struct {
	cfg config.ToolConfig
}

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

func (c *Client) Call(ctx context.Context, req *GoodsAddRequest) (*GoodsAddResponse, error) {
	apiReq, _ := util.StructToMap(req)

	r := l_request.Request{
		Method: "Post",
		Url:    c.cfg.BaseURL,
		Json:   apiReq,
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
	}

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

	type resType struct {
		Code int    `json:"code"`
		Msg  string `json:"message"`
		Data struct {
			Id int `json:"id"` // 商品 ID
		} `json:"data"`
	}

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

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

	toolResp := &GoodsAddResponse{
		PreviewUrl: c.cfg.AddURL,
		SpuCode:    req.SpuCode,
		Id:         resData.Data.Id,
	}

	return toolResp, nil
}
