package agent

import (
	"context"
	"errors"
	"wechat-api/ent/wx"

	"wechat-api/ent/agent"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *DeleteAgentLogic) DeleteAgent(req *types.IDsReq) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	if len(req.Ids) == 0 {
		return nil, errors.New("ids参数不能为空")
	}

	// 删除AI角色之前要检查他是否被某账号所使用
	count, _ := l.svcCtx.DB.Wx.Query().Where(wx.AgentIDIn(req.Ids...)).Count(l.ctx)
	if count > 0 {
		return nil, errors.New("有账号在使用该AI角色，请取消关联后再尝试删除")
	}

	_, err := l.svcCtx.DB.Agent.Delete().Where(agent.IDIn(req.Ids...), agent.OrganizationID(organizationId)).Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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