package agent

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

	"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 UpdateAgentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateAgentLogic) UpdateAgent(req *types.AgentInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	if *req.Id <= 0 {
		l.Error("记录ID不存在")
		return nil, errors.New("记录ID不存在")
	}

	item, err := l.svcCtx.DB.Agent.Query().Where(agent.ID(*req.Id), agent.OrganizationID(organizationId)).First(l.ctx)
	if err != nil && ent.IsNotFound(err) {
		return nil, errors.New("记录不存在")
	}

	// 如果是下架AI角色，则需要判断是否有账号在关联该AI角色，如果有不让修改
	if item.Status == 1 && req.Status != nil && *req.Status == 2 {
		count, _ := l.svcCtx.DB.Wx.Query().Where(wx.AgentID(*req.Id)).Count(l.ctx)
		if count > 0 {
			return nil, errors.New("有账号在使用该AI角色，请取消关联后再尝试禁用")
		}
	}

	err = l.svcCtx.DB.Agent.UpdateOneID(*req.Id).
		SetNotNilName(req.Name).
		SetNotNilRole(req.Role).
		SetNotNilStatus(req.Status).
		SetNotNilBackground(req.Background).
		SetNotNilExamples(req.Examples).
		Exec(l.ctx)

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

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