package fastgpt

import (
	"bytes"
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"strconv"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

type UpdateAppLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateAppLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAppLogic {
	return &UpdateAppLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *UpdateAppLogic) UpdateApp(req *types.UpdateAppsReq) (resp *types.BaseMsgResp, err error) {
	intro := ""
	if req.Intro != nil {
		intro = *req.Intro
	}
	organizationId := l.ctx.Value("organizationId").(uint64)

	organizationIdStr := strconv.FormatUint(organizationId, 10)
	token, err := GetToken(organizationIdStr)
	if err != nil {
		return nil, fmt.Errorf("invalid token")
	}

	AppUpdate(req.Id, req.Name, intro, token)

	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
}

func AppUpdate(id string, name string, intro string, token string) {
	url := fmt.Sprintf("https://fastgpt.gkscrm.com/api/core/app/update?appId=%s", id)
	jsonStr := fmt.Sprintf(`{"name":"%s","intro":"%s"}`, name, intro)
	requestBody := []byte(jsonStr)

	// 创建一个新的请求
	req1, err := http.NewRequest("PUT", url, bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	// 设置请求头
	req1.Header.Set("Content-Type", "application/json")
	req1.Header.Set("Cookie", fmt.Sprintf("fastgpt_token=%s", token))

	// 使用 http.Client 发送请求
	client := &http.Client{}
	resp1, err := client.Do(req1)
	if err != nil {
		fmt.Printf("Error sending request: %v\n", err)
		return
	}
	defer resp1.Body.Close()

	return
}
