package supplier_search

import (
	"ai_scheduler/internal/config"
	"ai_scheduler/internal/pkg/l_request"
	"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, name string) (int, error) {
	if name == "" {
		// 如果没有供应商名，返回0，不报错，由上层业务决定是否允许
		return 0, nil
	}

	reqBody := SearchRequest{
		Page:  1,
		Limit: 1,
		Search: SearchCondition{
			Name: name,
		},
	}

	apiReq := make(map[string]interface{})
	bytes, _ := json.Marshal(reqBody)
	_ = json.Unmarshal(bytes, &apiReq)

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

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

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

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

	if len(resData.Data.List) == 0 {
		return 0, fmt.Errorf("供应商不存在")
	}

	return resData.Data.List[0].ID, nil
}
