package order_after_reseller_batch

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

func Call(ctx context.Context, cfg config.ToolConfig, orderNumbers []string) (*OrderAfterSaleResellerBatchResponse, error) {
	if len(orderNumbers) == 0 {
		return nil, errors.New("批充订单号不能为空")
	}
	token := util.GetTokenFromContext(ctx)
	if token == "" {
		return nil, errors.New("token 未注入")
	}
	r := l_request.Request{
		Url: cfg.BaseURL,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", token),
		},
		Method: "POST",
		Json: map[string]any{
			"order_numbers": orderNumbers,
			"order_type":    2,
		},
	}
	res, err := r.Send()
	if err != nil {
		return nil, err
	}

	response := &OrderAfterSaleResellerBatchResponse{}
	if err = json.Unmarshal(res.Content, &response); err != nil {
		return nil, err
	}
	if response.Code != 200 {
		return nil, fmt.Errorf("售后订单查询异常: %s", response.Error)
	}
	if len(response.Data.Data) == 0 {
		return nil, errors.New("未查询到相应售后订单，请核实订单号是否正确")
	}
	return response, nil
}
