package agent

import (
	"context"
	"fmt"
	"sync"
	"wechat-api/hook/fastgpt"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *BatchDeleteAgentDataLogic) BatchDeleteAgentData(req *types.BatchDeleteIds) (*types.BaseDataInfo, error) {
	var success, fail int

	if len(req.Ids) > 0 {
		var wg sync.WaitGroup
		for _, sid := range req.Ids {
			wg.Add(1)
			go func(sid string) {
				defer wg.Done()

				response, err := fastgpt.DeleteData(sid)
				fmt.Printf("id=%s, response=%+v\n", sid, response)
				if err != nil {
					fail++
					fmt.Printf("delete fastgpt data failed:%v\n", err)
				}
				if response != nil && response.Code == 200 {
					success++
				}
			}(sid)
		}
		wg.Wait()
	}

	resp := types.BaseDataInfo{}
	resp.Msg = fmt.Sprintf("succeed %d rows, fail %d rows", success, fail)
	return &resp, nil
}
